什么是“嵌套量词”,为什么它导致我的正则表达式失败?

我有这个正则表达式,我在正则表达式伙伴中构建和测试。

"_ [ 0-9]{10}+ {1}+[ 0-9]{10}+ {2}+[ 0-9]{6}+ {2}[ 0-9]{2}" 

当我在.Net C#中使用它时

我收到了例外

 "parsing \"_ [ 0-9]{10}+ +[ 0-9]{10}+ +[ 0-9]{6}+ [ 0-9]{2}\" - Nested quantifier +." 

这个错误是什么意思? 显然.net不喜欢这个表达。

这是正则表达式的伙伴,所以你可以用正则表达式理解我的意图……

 _ [ 0-9]{10}+ {1}+[ 0-9]{10}+ {2}+[ 0-9]{6}+ {2}[ 0-9]{2} Match the characters "_ " literally «_ » Match a single character present in the list below «[ 0-9]{10}+» Exactly 10 times «{10}+» The character " " « » A character in the range between "0" and "9" «0-9» Match the character " " literally « {1}+» Exactly 1 times «{1}+» Match a single character present in the list below «[ 0-9]{10}+» Exactly 10 times «{10}+» The character " " « » A character in the range between "0" and "9" «0-9» Match the character " " literally « {2}+» Exactly 2 times «{2}+» Match a single character present in the list below «[ 0-9]{6}+» Exactly 6 times «{6}+» The character " " « » A character in the range between "0" and "9" «0-9» Match the character " " literally « {2}» Exactly 2 times «{2}» Match a single character present in the list below «[ 0-9]{2}» Exactly 2 times «{2}» The character " " « » A character in the range between "0" and "9" «0-9» 

简而言之…

什么是嵌套量词?

.NET抱怨{n}样式量词之后的+ ,因为它没有任何意义。 {n}表示完全匹配给定组的n。 +表示匹配给定组中的一个或多个。 删除+ ‘,它将编译好。

 "_ [ 0-9]{10} {1}[ 0-9]{10} {2}[ 0-9]{6} {2}[ 0-9]{2}" 

.NET不支持占有量词

 {10}+ 

但是,{10}应该具有完全相同的效果。 +如果最长的匹配失败,则避免回溯并尝试更短的匹配,但是因为{10}只能匹配10个字符才能开始,这并没有实现太多。

 "_ [ 0-9]{10} [ 0-9]{10} {2}[ 0-9]{6} {2}[ 0-9]{2}" 

应该没事。 我也放弃了“{1} +”位。由于它只匹配一次,“A {1} +”相当于“A”。

编辑正如Porges所说,如果你确实需要.NET中的占有量词,那么primefaces组给出相同的function(>[0-9]*)相当于[0-9]*+

他们是对的。 此版本的正则表达式不会失败:

(_ [ 0-9]{10})+(\s{1})+([ 0-9]{10})+(\s{2})+([ 0-9]{6})+\s{2}[ 0-9]{2}

请注意使用parens创建组,然后可以重复一次或多次。 此外,您应该更具体并使用\ s而不是空格,因为模式空白可能具有或不具有重要性。

顺便说一下,这个正则表达式看起来并不那么有用。 您可能想要提出另一个问题:“如何使用正则表达式匹配此模式?”

如果在RegexBuddy顶部的工具栏中选择.NET flavor,RegexBuddy将指示.NET不支持占有量词,例如{10} +。

由于{10}仅允许一个特定数量的重复,使其变得懒惰或占有欲是没有意义的,即使它在支持惰性和/或占有量词的正则表达式语法中在语法上有效。 从正则表达式中删除+符号将使其适用于.NET。

在其他情况下,在RegexBuddy的“创建”选项卡中双击有关占有量词的错误。 然后,RegexBuddy将用function等效的primefaces组替换占有量词。

如果您在RegexBuddy的“使用”选项卡上生成.NET语言的源代码片段,RegexBuddy将自动替换源代码段中正则表达式中的占有量词。