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

ctr*_*yan 14 .net c# regex

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

"_ [ 0-9]{10}+ {1}+[ 0-9]{10}+ {2}+[ 0-9]{6}+ {2}[ 0-9]{2}"
Run Code Online (Sandbox Code Playgroud)

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

我收到了例外

"parsing \"_ [ 0-9]{10}+ +[ 0-9]{10}+  +[ 0-9]{6}+  [ 0-9]{2}\" - Nested quantifier +."
Run Code Online (Sandbox Code Playgroud)

这个错误是什么意思?显然.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»
Run Code Online (Sandbox Code Playgroud)

简而言之...

什么是嵌套量词?

ste*_*son 13

.NET不支持占有量词

{10}+
Run Code Online (Sandbox Code Playgroud)

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

"_ [ 0-9]{10} [ 0-9]{10} {2}[ 0-9]{6} {2}[ 0-9]{2}"
Run Code Online (Sandbox Code Playgroud)

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

编辑 作为Porges说,如果你确实需要在.NET中占有量词,那么原子团给予相同的功能与(>[0-9]*)等价于[0-9]*+.


Dun*_*can 9

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

"_ [ 0-9]{10} {1}[ 0-9]{10} {2}[ 0-9]{6} {2}[ 0-9]{2}"
Run Code Online (Sandbox Code Playgroud)

  • 在某些正则表达式中,{min,max} +是占有量量词,但.Net不支持它们.如果您正在使用Regex好友,可以通过右键单击合成窗格并从下拉列表中选择"Flavor"来告诉您正在使用哪种正则表达式. (3认同)