.NET Regex Lookbehind不贪心

pap*_*zzo 5 .net regex lookbehind

如何让后视变得贪婪?
在这种情况下,我希望lookbehind消耗:if is存在.

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'
Run Code Online (Sandbox Code Playgroud)

我找到了一个解决方法

@"(?i)(?<=\bsubject:?\s+).*?(?=\s*\r?$)"
Run Code Online (Sandbox Code Playgroud)

只要你放一些肯定的后?那么它可选择贪婪的游戏.出于同样的原因,我不得不将$放在前面.
但是如果你需要以可选的贪婪结束,那么必须使用下面接受的答案.

por*_*ges 4

有趣的是,我没有意识到他们在 .NET 中是非贪婪的。这是一种解决方案:

(?<=from(:|(?!:)))
Run Code Online (Sandbox Code Playgroud)

这意味着:

(
  :     # match a ':'
  |
  (?!:) # otherwise match nothing (only if the next character isn't a ':')
) 
Run Code Online (Sandbox Code Playgroud)

这会强制它匹配“:”(如果存在)。