in reply to Re: Req Expression translation
in thread Req Expression translation

I am using it as:
anotherwordhere\s+.*? wordhere
I am trying to fetch a match on a word before "wordhere" and it does work but not sure what the "?" does.

You said "?" acts as non gready here. Please explain more on this? I am still not sure what "?" does?

Replies are listed 'Best First'.
Re: Re: Re: Req Expression translation
by sauoq (Abbot) on Jun 14, 2003 at 03:49 UTC

    Sometimes an example helps...

    #!/usr/bin/perl -w use strict; my $string = 'anotherwordhere foobar wordhere baz qux wordhere'; $string =~ /anotherwordhere\s+(.*?) wordhere/; print "Non-greedy match: '$1'\n"; $string =~ /anotherwordhere\s+(.*) wordhere/; print "Greedy match : '$1'\n";
    That prints:
    Non-greedy match: 'foobar' Greedy match : 'foobar wordhere baz qux'
    Do you see why it is called non-greedy? It matches as little as it has to in order to get the job done. The normal (greedy) behavior is to match as much as it can (and still get the job done.)

    The getting the job done part is what's most important. The distinction between greedy and non-greedy is only significant when there is both a short and a long way to get the job done. If you changed the string in that example so that it ended in "wordnothere" , both would match the same thing.

    I hope that clears it up a bit. Some experimentation will probably help your understanding.

    -sauoq
    "My two cents aren't worth a dime.";
    
      Thanks!