正则表达式中的模运算符

时间:2017-02-12 21:04:56

标签: regex modulo regular-language

我正在尝试编写一个正则表达式来接受任何二进制字符串,唯一的标准是0的数量不是3的因数([数量为0]%3!= 0)。如何实现这一目标?

3 个答案:

答案 0 :(得分:0)

从我能够查找的内容来看,仅使用正则表达式是不可能的。您可能需要获取0的数量并在其他代码中自行解析。对于每场比赛,请检查result % 3 != 0

答案 1 :(得分:0)

您可以使用.match()来实现此目的。 .match()返回与正则表达式匹配的所有匹配项的数组。在返回的数组.length上使用modulo将告诉您0的数量是否可以被3整除。

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

答案 2 :(得分:0)

如果你的正则表达式支持recursive pattern,你可以使用它:

^(1*01*)(?1)?(?:(?1)(?1)(?1))*1*$

如果没有,请将所有(?1)替换为(1*01*)

<强>解释

^               : 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.
相关问题