var someString = '012345167891abcd1efghi1jklmn';
var numOfOnes = someString.match(/(1)/g)
// numOfOnes = ["1", "1", "1", "1", "1"]
numOfOnes.length % 3 // will return 2, so it's not a factor of 3
^ : begining of string
( : start group 1
1*01* : that contains 0 or more 1, one 0 and 0 or more 1
) : end group
At this time, we have one 0
(?1)? : Same pattern as group 1 (ie. 1*01*), optional
we have now one or two 0
(?: : non capture group
(?1)(?1)(?1): pattern 1 repeated 3 times
)* : 0 or more times
we have one or two 0 followed by three 0,
so the number of zeros modulo 3 != 0
1* : 0 or more 1
$ : end of string.
4条答案
按热度按时间bhmjp9jg1#
您可以使用
.match()
来实现这一点。.match()
返回一个数组,其中包含所有匹配正则表达式的示例。对返回的数组.length
使用模将告诉您0的数量是否可被3整除。gcmastyq2#
如果你的regex flavor支持递归模式,你可以这样做:
如果没有,则将所有
(?1)
替换为(1*01*)
说明:
hwamh0ep3#
^(([^0]*0){3})*[^0]*$
检查是否有3个零的倍数,你可以在$
之前放一个(0[^0]*){1,2}
,或者用一个负的前向包起来。qc6wkl3g4#
从我所能查到的来看,仅仅用正则表达式是不可能的。您可能需要获取0的个数,并在其他代码中自己解析它。对于每个匹配项,检查
result % 3 != 0