【发布时间】:2021-03-02 19:59:03
【问题描述】:
注意:
-
观察到的行为是正确的,但起初可能令人惊讶;对我来说是这样,我认为对其他人来说可能也是如此——尽管对于那些非常熟悉正则表达式引擎的人来说可能不是。
-
重复建议的重复,Regex lookahead, lookbehind and atomic groups,包含关于环视断言的一般信息,但没有解决手头的具体误解,如更详细讨论的那样在下面的 cmets 中。
使用 greedy,根据定义,positive look-behind assertion 内的 variable-width 子表达式可能会表现出令人惊讶的行为。
为方便起见,示例使用 PowerShell,但该行为通常适用于 .NET 正则表达式引擎:
这个命令按我的直觉工作:
# OK:
# The subexpression matches greedily from the start up to and
# including the last "_", and, by including the matched string ($&)
# in the replacement string, effectively inserts "|" there - and only there.
PS> 'a_b_c' -replace '^.+_', '$&|'
a_b_|c
以下使用肯定的后向断言(?<=...) 的命令看似等效,但不是:
# CORRECT, but SURPRISING:
# Use a positive lookbehind assertion to *seemingly* match
# only up to and including the last "_", and insert a "|" there.
PS> 'a_b_c' -replace '(?<=^.+_)', '|'
a_|b_|c # !! *multiple* insertions were performed
为什么不等价?为什么要执行多次插入?
【问题讨论】:
-
@WiktorStribiżew 重新发布相同的信息而不解决相反的问题是没有帮助的。下面答案中的 cmets 解释了为什么您的链接没有帮助。您这次发布的附加链接也无济于事,可以通过查找术语“可变宽度”、“可变长度”和“贪婪”来轻松验证 - this 问题是关于 - 那里:你不会找到他们。
-
只是为了避免未来的读者可能会浪费精力,并平衡上面评论中的喊叫声:所谓的重复一般描述了外观的行为-围绕断言。他们没有解决这个问题的具体误解。虽然您可以假设从链接的帖子中推断解释,但这样的推断远非显而易见。 只有下面的答案提供了具体的、(希望)清晰的解释。
标签: .net regex regex-lookarounds regex-greedy