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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |