Search code examples
.netregexlookbehind

.NET Regex Lookbehind Not Greedy


How to get the lookbehind to be greedy?
In this case I want the lookbehind to consume the : if is is present.

m = Regex.Match("From: John", @"(?i)(?<=from:)....");
// returns ' Jon' what I expect not a problem just an example

m = Regex.Match("From: John", @"(?i)(?<=from:?)....");
// returns ': Jo'
// I want it to return ' Jon'

I found a work around

@"(?i)(?<=\bsubject:?\s+).*?(?=\s*\r?$)"

As long as you put some affirmative after the ? then it takes the optional greedy out of play. For the same reason I had to put the $ in the look forward.
But if you need to end on an optional greedy then have to go with the accepted answer below.


Solution

  • Interesting, I didn't realise they were non-greedy in .NET. Here is one solution:

    (?<=from(:|(?!:)))
    

    This means:

    (
      :     # match a ':'
      |
      (?!:) # otherwise match nothing (only if the next character isn't a ':')
    ) 
    

    This forces it to match the ':' if present.