in reply to Match only last occurrence

/text: \d{3}.*?$/sa;

Update: See tye's important observation and correction in the reply. You could instead anchor the regex at the start to have it match the last. eg:

/^.*text: \d{3}/sa;

Replies are listed 'Best First'.
Re^2: Match only last occurrence (left-most then longest)
by tye (Sage) on May 31, 2016 at 14:46 UTC

    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        

      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.
      Anti-greediness doesn't trump "left-most first". It only trumps "longest first".

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

Re^2: Match only last occurrence
by sotona (Scribe) on May 31, 2016 at 14:47 UTC
    matches the first occurence
    Sapienti sat.