in reply to Re^2: help with lazy matching
in thread help with lazy matching

The non-greedy modifier simply means "match as little as possible while still getting a successful match". All regex matches in Perl Compatible Regular Expressions always match leftmost first; in your case the first slash. Where the non-greedy operator might have worked, for example, is if you wanted to only match 'foo'. Then you could write:

if ( /\/(.+?)\// )

This will match the first slash, then non-greedily match any other characters until another slash is reached. If you didn't use the non-greedy modifier here, you would match everything between the first and last slash (i.e. 'foo/bar/baz').

--Nick

Replies are listed 'Best First'.
Re^4: help with lazy matching
by Special_K (Pilgrim) on Jan 05, 2015 at 23:07 UTC
    I think the source of my confusion was not knowing that regular expressions in perl always start matching from the left side. If the regular expression could start matching from anywhere, then using the non-greedy modifier could give the behavior I was expecting in my original post, i.e. matching "bar".

      This is not a Perl-specific issue. The "Leftmost" rule is one of the features of a NFA-based regular expression engine, which includes Perl, PHP, Python, and most other commonly used regular expression implementations. So now that you're aware of it with respect to Perl, you've learned something that can be applied to most other languages that implement regexes as well! :)


      Dave