Search code examples
regexregex-lookaroundsregex-greedy

RegEx for enforcing and finding the last match


I am trying to extract a part of a name from a string. I almost have it, but something isn't right where I am using a positive lookahead.

Here is my regex: (?=s\s(.*?)$)

I have marked all the results I want with bold text.

Trittbergets Ronja

Minitiger's Samanta Junior

Björntorpets Cita

Sors Kelly's Majsskalle

The problem is that Kelly's Majsskalle gets returned, when it should only select Majsskalle.

Here is a link to regex101 for debugging: https://regex101.com/r/PZWxr7/1

How do I get the lookahead to disregard the first match?


Solution

  • You need to enforce regular expression engine to find the last match using a dot-star:

    ^.*s\s(.*)$
    

    A .* consumes everything up to a linebreak immediately then engine backtracks to match the next pattern.

    See live demo here

    or use a tempered dot:

    s(?= ((?:(?!s ).)+)$)
          ^^^^^^^^^^
      Match a byte only if we are not pointing at a `s[ ]`
    

    See live demo here

    Note: the former is the better solution.