[Gambas-user] Regular expressions

Rob sourceforge-raindog2 at ...94...
Fri Oct 31 22:40:03 CET 2008


On Friday 31 October 2008 12:09, Markus Schatten wrote:
> Thanks a lot for the links, they were very helpfull. Is there a way to
> use a regex for looping through all matches? Something like scan(....)
> in a for each loop or findall in python-re? I was able to figure out
> that the Text property holds the first match, Submatches is an array of
> given submatches (in parenthesis) and Offset holds the index if the
> first match. There seem to be no other properties defined...

I haven't created a method to do this yet because pcre doesn't include such 
a mechanism natively, but it's certainly possible.  Here's some 
pseudo-code, which should at least compile.  I had to add the extra 'and 
subj <> ""' test because at least in my copy of gb.pcre, there's a bug 
where if you pass it an empty string it throws an error as if you passed 
it a null string.  I'm building the latest Gambas now to see if Benoit 
fixed that when he fixed the rest of my bad code in 2.7.0. ;)

function FindAll(subj as string, pattern as string) as String[]
	dim re as Regexp
	dim matches as new String[]
	re = new Regexp(subj, pattern)
	do while re.offset >= 0 and subj <> ""
		matches.push(re.text)
		if len(subj) > len(re.text) then
			subj = mid(subj, re.offset + len(re.text) + 1)
 		else
			subj = ""	
		end if
		if subj <> "" then re.exec(subj)
	loop
	return matches
end

Rob




More information about the User mailing list