Thanks for writing. Your code works for this example but doesn't get exactly
what I need. It's important to me to keep $1 and $2 separate because Yeas
and Nays are paired together (these are votes on bills). But sometimes, you
only have Yeas (eg, a unanimous vote).

That is why I want to see:

123             <- from the first yea ($1)
(nothing)       <- no nay! ($2)
456             <- from the second yea ($1)
789             <- from the second nay ($2)

Hence why I put a ? After the (?:Nay (.*?)x) regexp; the idea being this can
appear zero or one times. But if I do this, I get no matches on the 'nays'
or $2.

-----Original Message-----
From: Randy W. Sims [mailto:[EMAIL PROTECTED] 
Sent: Sunday, April 04, 2004 9:30 PM
To: [EMAIL PROTECTED]
Cc: [EMAIL PROTECTED]
Subject: Re: Regular expression question: non-greedy matches


Boris Shor wrote:
> 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>




--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to