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?
5 Answers 5
^((1*0){3})*1*$ checks that there is a multiple of 3 zeros, and you can just put a (01*){1,2} before the $, or wrap in in a negative lookahead.
Comments
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
Comments
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.
Comments
The cases to match are:
- 1 or 2 zeroes
- 4 or 5 zeroes
- 7 or 8 zeroes
- ...
Which simplifies to 3n+1 or 3n+2 zeros for non-negative integers n.
3n+2 == (3n+1)+1
So:
^(000)*00?$
But ones can appear before or after any zero, so:
^1*(01*01*01*)*01*0?1*$
Comments
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