.net正则表达式,条件查找后和捕获组 [英] .net regex with condition lookbehind and capture group
问题描述
模式: a(?(?< ;!))b(c)
输入: abc
说明:如果向后看不是空格,则条件应与空间匹配。
Desription: Condition should match space, if lookbehind is not a space.
它匹配正确,但是捕获组$ 1为空(包含c的实例)。
It matches correct, but the capture group $1 is empty (instad of containing c).
.net regex还是am这个问题?我错过了什么吗?
Is this a problem with .net regex or am I missing something?
示例: http://regexstorm.net/tester?p=a(%3f(%3f%3C!+)+)b +(c)&i = a + b + c
推荐答案
我不确定是否已记录此行为(如果是)然后我没有找到它),而是使用了一个条件构造,其中包括一个明确的零宽度断言作为其表达式(?(?(ex = expression)yes | no)
会覆盖非常多的编号捕获组(将其清空)。您可以通过在RegEx下面运行来确认这一点:
I'm not sure if this behavior is documented or not (if yes then I didn't find it) but using a conditional construct including an explicit zero-width assertion as its expression (?(?=expression)yes|no)
overrides the very next numbered capturing group (empties it). You can confirm this by running below RegEx:
a(?(?<! ) )b (c)()
克服此问题的四种方法:
Four ways to overcome this issue:
-
在表达式中将表达式括在@DmitryEgorov指出的括号中(这也使第二个
捕获组保持完整),并且不包含在结果中-正确的
方法:
Enclosing expression in parentheses noted by @DmitryEgorov (that also keeps second capturing group intact) and is not included in result - the right way:
a(?((?<! )) )b (c)
此行为仅适用于未命名的捕获组
(默认),您可以使用命名的捕获组:
As this behavior is only applied to unnamed capturing groups (default) you can get expected result using a named capturing group:
a(?(?<! ) )b (?<first>c)
在(c)$之间添加任意一个捕获组c $ c>和有条件的:
a(?(?<! ) )(b) (c)
尽可能避免使用这样的表达式 。例如:
a(?( ) )b (c)
这篇关于.net正则表达式,条件查找后和捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!