我有0和1的字符串。我想要一个正则表达式,使得0的数量小于1的数量。
例子:
0111 - match (there is 1x0 and 3x1 and 1 < 3)
00011 - pattern fails (3x0 and 2x1 but 3<2 is false)
0101010 - pattern fails (4x0 and 3x1 but 4<3 is false)
使用pcre以及可能的Perl,可以使用递归模式:
^((?:0(?1)??1|1(?1)??0)*+)(?:1(?1))+$
细节:
^
( # group 1: matches balanced 0 and 1
(?:
0(?1)??1 # part that starts with 0 and ends with 1
# (?1) calls the group 1 subpattern itself (recursion)
|
1(?1)??0 # same thing for 1 ... 0
)*+ # repeat
)
(?:
1
(?1)
)+ # ensure there's at least one 1 that isn't matched by (?1)
$
使用.net正则表达式引擎:
^(?>(?<c>0)|(?<-c>1))*(?(c)(?!$))(?:1(?>(?<c>0)|(?<-c>1))*(?(c)(?!$)))+$
这次更加直观:
(?<c>...)
增加计数器c并(?<-c>...)
减少相同的计数器。(?(c)(?!$))
当计数器c不为零((?!$)
始终失败的子模式)时,条件条件失败。
此模式的全局结构与以前的相同:
^ (balanced parts)* (?: 1 (balanced parts)* )+ $
pcre的另一种可能的结构是:
^ (?: balanced parts | (1) )*+ (force to fail if capture group doesn't exist) $
pcre:
^(?:((?:0(?1)?1|1(?1)?0)+)|(1))*+(?(2)|(*F))$
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句