Reputation: 4565
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?
Upvotes: 2
Views: 9301
Reputation: 41
^((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.
Upvotes: 0
Reputation: 91528
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.
Upvotes: 0
Reputation: 62871
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
Upvotes: 0
Reputation: 947
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
Upvotes: -1