gpt4 book ai didi

.NET 正则表达式 Lookbehind 不贪婪

转载 作者:行者123 更新时间:2023-12-03 02:15:28 25 4
gpt4 key购买 nike

如何让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'

我找到了解决办法

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

只要在 ? 后面加一些肯定即可。那么它就会使可选的贪婪不再发挥作用。出于同样的原因,我必须将 $ 放入期待中。
但如果您需要以可选的贪婪结束,那么必须采用下面接受的答案。

最佳答案

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

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

这意味着:

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

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

关于.NET 正则表达式 Lookbehind 不贪婪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12272445/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com