Modulo operator in a regular expression

送分小仙女□ 提交于 2021-01-27 22:43:46

问题


I am attempting to write a regular expression to accept any binary strings with the only criteria being that the number of 0s is not a factor of 3 ([number of 0s] % 3 != 0). How can this be achieved?


回答1:


You can use .match() to achieve this. .match() returns an array of all occurrences matching the regex. Using modulo on the returned array's .length will tell you if the number of 0s is divisible by 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:


If your regex flavour supports recursive pattern, you could use this:

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

If it doesn't, replace all (?1) by (1*01*)

Explanation:

^               : 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.



回答3:


From what I've been able to look up, it's not possible to do with just regex. You probably need to get the number of 0s and parse it yourself in some other code. For each match, check if result % 3 != 0



来源:https://stackoverflow.com/questions/42193223/modulo-operator-in-a-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!