tags:

views:

55

answers:

2

Hi,

First, this question may have been asked before, but I'm not sure what phrase to search on.

I have a string:

Maaaa

I have a pattern:

aaa

I would like to match twice, giving me starting indices of 1 and 2. But of course I only get a single match (start index 1), because the regex engine gobbles up all 3 "a"s and can't use them again, leaving me with 1 "a" which doesn't match.

How do I solve this?

Thanks!

+9  A: 

You could use a lookahead assertion to find an a followed by 2 a's

a(?=aa)
Paul Creasey
Adding a little color commentary, you can find out more about [zero-width] lookahead assertions here: http://www.regular-expressions.info/lookaround.html
Marc Bollinger
A: 

The man perlre manpage suggests:

 my @a;
 "Maaaa" =~ /aaa(?{push @a,$&})(*FAIL)/;
 print join "\n",@a;
 print "\n";

which yields

aaa
aaa
Alex Brown
Is there any reason whatsoever to use this ugliness instead of the simple 7-character regex with a lookahead?
Max Shawabkeh
heh, no. I just thought it was interesting.
Alex Brown