Multiple distinct RegExMatch matches for v2

Put simple Tips and Tricks that are not entire Tutorials in this forum
User avatar
RUBn
Posts: 51
Joined: 27 Nov 2013, 05:12
Contact:

Multiple distinct RegExMatch matches for v2

13 Nov 2023, 04:48

I didn't find the answer on this forum for storing multiple regex matches in v2 with short, most efficient code which I did find in v1, so I thought I put it here since I found the solution. It happens also to be distinct.

My main quest was for these 2 lines:

Code: Select all

p := 1, m := {Len:0}
while p := RegExMatch(Haystack, 'this:"([^"]+)"' , &m, p + m.Len)
Full code:

Code: Select all

~^n::
{
	test:="", mtgaMatches:=[], Haystack:='blabla bla bla this:"xx" bla bla bla bla this:"xx" bla  this:"yy" bla bla bla this:"zz"'
	p := 1, m := {Len:0}
	while p := RegExMatch(Haystack, 'this:"([^"]+)"' , &m, p + m.Len) {
			if HasVal(mtgaMatches, m[1])
				Continue
			mtgaMatches.Push(m[1])
	}
	for match in mtgaMatches
		test.=match
	MsgBox test
}


HasVal(haystack, needle) {
	for index, value in haystack
		if (value == needle)
			return index
	if !IsObject(haystack)
		throw ValueError("Bad haystack!", -1, haystack)
	return 0
}

[Mod action: Moved topic from “Ask for Help (v2)”.]
User avatar
NPerovic
Posts: 35
Joined: 31 Dec 2022, 01:25
Contact:

Re: Multiple distinct RegExMatch matches for v2

14 Nov 2023, 20:20

What is HasVal() for?
You can still get the same result without it, isn't it?

Code: Select all

#Requires AutoHotkey v2
~^n::{
	test     := "", mtgaMatches := []
	Haystack := 'blabla bla bla this:"xx" bla bla bla bla this:"xx" bla  this:"yy" bla bla bla this:"zz"'
	while p := RegExMatch(Haystack, 'this:"([^"]+)"', &m, (p ?? 1) + (m := m ?? {Len:0}).Len)
		mtgaMatches.push(test .= m[1])
	MsgBox test
}

There's another way to do so with Regular Expression Callouts

Code: Select all

#Requires AutoHotkey v2
~^n::{
	test := "", mtgaMatches := []
	RegExMatch('blabla bla bla this:"xx" bla bla bla bla this:"xx" bla  this:"yy" bla bla bla this:"zz"', 'S)this:"\K[^"]++(?CCallout)')
	Callout(m, *) => (mtgaMatches.Push(test .= m[]), 1)
	MsgBox(test)
}

If you just want to join the matched strings together, you can just use RegExReplace.

Code: Select all

MsgBox(RegExReplace('blabla bla bla this:"xx" bla bla bla bla this:"xx" bla  this:"yy" bla bla bla this:"zz"', '.+?this:"([^"]+)"', "$1"))
✨ Dark Theme for Everything
✨ Other Scripts


Return to “Tips and Tricks”

Who is online

Users browsing this forum: No registered users and 12 guests