Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.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.

like image 205
paparazzo Avatar asked Oct 06 '22 17:10

paparazzo


1 Answers

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.

like image 168
porges Avatar answered Oct 10 '22 01:10

porges