As already mentioned, regexes work from left to right and the regex engine will not backtrack if if succeeds. Your "lazy matching" would work if you wanted to get only the first part of the string, but here, when it gets to the end of the string, it has succeeded and has no reason to take only the end part.

In theory, you could get around that and use a non-greedy quantifier by first reversing the string and then reversing the result, with this:

$ perl -E 'my $c = reverse "/foo/bar/baz/bat"; say "matched ", scal +ar reverse ($1) if $c =~ m{(.+?)/};' matched bat
But that's a bit ugly and unnatural.

The alternative if to forget about non-greedy quantifier for such a case and use character class, as in the old days where there was no non-greedy quantifier:

$ perl -E 'my $c = "/foo/bar/baz/bat"; say "matched $1" if $c =~ m{/ +(\w+)$};' matched bat
or:
$ perl -E 'my $c = "/foo/bar/baz/bat"; say "matched $1" if $c =~ m{/( +[^/]+)$};' matched bat
Please also note how I used { } as regex delimiters (theare are many others that you can use, most non-letter or number characters, such as []  (), ##, §§,etc.) so that I did not have to escape the /.

It was not really mandatory in such a simple example, but it often makes life easier when you have slashes in your regex.

Update: modified the first code snippet which did not reverse the result. Thanks to AnomalousMonk for pointing out the mistake.


In reply to Re: help with lazy matching by Laurent_R
in thread help with lazy matching by Special_K

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.