Pattern matches always find the leftmost possible match. Greediness does not change this, it only affects how soon a quantifier will consider itself satisfied. In your case, / finds the leftmost slash in the string, .*? then tries to match nothing, which fails because the following $ needs the end of string to succeed, and then successively keeps trying to match only one more character, which keeps failing because the $ does not succeed, until the .*? has matched all of the string after the first slash. Since all parts of the pattern then succeed, you have a match.

You can use this knowledge to combine the leftmost match behaviour with greediness to make them work for you. Try this:

m{ .* / (.*) $ }msx

What happens here is that the first greedy .* will match the entire string. But then the / wants a slash, and that fails, since there’s no slash after the end of the string; so the .* is forced to concede one character. The / will keep failing and the .* will keep conceding characters, until it is matching only up to the character before the last slash in the string, at which point the / can match that slash and thus succeed. The parenthesised .* will then swallow the rest of the string, which means the $ immediately succeeds.

Now the parenthesised quantifier has matched exactly what you wanted.

Makeshifts last the longest.


In reply to Re: Regex: Matching last of repeated character to end of string by Aristotle
in thread Regex: Matching last of repeated character to end of string by loris

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.