in reply to Re: Match only last occurrence
in thread Match only last occurrence

Actually, that doesn't work. The regex engine finds the first match of "text: \d{3}" and then tries to match ".*?" anti-greedily but still matches .*? before it would backtrack and try matching the second match. Anti-greediness doesn't trump "left-most first". It only trumps "longest first".

I think the simplest approach is:

my $match = ( /text: ([0-9]{3})/g )[-1];

But if you want to have the regex enforce the "last" part, then you have to get more complicated:

my( $match ) = /text: ([0-9]{3})(?:(?!text: [0-9]{3}).)*$/s;

- tye        

Replies are listed 'Best First'.
Re^3: Match only last occurrence (left-most then longest)
by sotona (Scribe) on May 31, 2016 at 14:52 UTC
    That's it! I didn't figure out I have to repeat the pattern to match exactly the last occurrence.
    Thanks a lot!
    Sapienti sat.
Re^3: Match only last occurrence (left-most then longest)
by hippo (Archbishop) on May 31, 2016 at 15:08 UTC
    Anti-greediness doesn't trump "left-most first". It only trumps "longest first".

    How right you are - thanks for the spot and the correction.