Hello,
Perl beginner here. I am having difficulty with a regular expression that uses non-greedy matches. Here is a sample code snippet:
$test = "Yea 123xrandomYea 456xdumdumNay 789xpop"; while ($test =~ /Yea (.*?)x.*?(?:Nay (.*?)x)?/g) { print "$1\n"; print "$2\n"; }
The idea is that every 'phrase' is delimited with an 'x' and there are random letters between phrases.
I expect to see:
123
456 789
But instead I get:
123
456
Why don't I get the second part of the regular expression?
Well, the first thing that I notice is that you never capture anything in $2. We could get it to match the second time through, but it is never gonna match in the first iteration. That may be a clue that there is a better way.
Looking at the two parts of the regex, I see that they are basically the same except for 'Yea' vs 'Nay'. This indicates that alternation be usefull. Combining them, I get:
while ($test =~ /(?:Yea|Nay) (\d+)x/g) { print "$1\n"; }
Does this help?
Randy.
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED] <http://learn.perl.org/> <http://learn.perl.org/first-response>