Melly has asked for the wisdom of the Perl Monks concerning the following question:
Hi Monkees
I got a very useful regex in answer to a question yesterday, but I'm confused as to why it's not a greedy regex.
Consider the following (similiar) regexs - the first one is the one that's puzzling me. The second is greedy as I'd expect; the third is non-greedy as I'd expect, but I don't understand why the first one is non-greedy as well.
$_ = 'fooxbarbar'; # Not greedy - why not? if(/(foo)(((?!bar).){1,5})bar/){ print "1 Matched:$1 $2\n"; } else{ print "1 Not Matched\n"; } # Greedy - as we'd expect if(/(foo)(?!bar)((.){1,5})bar/){ print "2 Matched:$1 $2\n"; } else{ print "2 Not Matched\n"; } # Not Greedy - as we'd expect if(/(foo)(?!bar)((.){1,5}?)bar/){ print "3 Matched:$1 $2\n"; } else{ print "3 Not Matched\n"; }
Any explanation most appreciated...
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Why isn't this regex greedy?
by demerphq (Chancellor) on Mar 17, 2006 at 10:02 UTC | |
by merlyn (Sage) on Mar 17, 2006 at 14:40 UTC | |
by Melly (Chaplain) on Mar 17, 2006 at 10:20 UTC | |
by demerphq (Chancellor) on Mar 17, 2006 at 10:44 UTC | |
|
Re: Why isn't this regex greedy?
by GrandFather (Saint) on Mar 17, 2006 at 10:24 UTC | |
|
Re: Why isn't this regex greedy?
by kettle (Beadle) on Mar 17, 2006 at 10:33 UTC |