.NET Regex Lookbehind is not greedy

How to make lookbehind be greedy?
In this case, I want lookbehind to consume: if 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 job around

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

As long as you put some affirmative after? then he gains an optional greedy exit from the game. For the same reason, I had to put $ on hold.
But if you need to end optional greed, then you need to go with the accepted answer below.

+5
source share
1 answer

Interestingly, I did not realize that they were not greedy in .NET. Here is one solution:

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

It means:

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

This makes it match ":" if present.

+4
source

All Articles