2

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?

asked Feb 12, 2017 at 21:04

5 Answers 5

1

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

answered Sep 26, 2023 at 9:20
Sign up to request clarification or add additional context in comments.

Comments

0

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
answered Feb 12, 2017 at 21:10

Comments

0

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.
answered Feb 13, 2017 at 11:00

Comments

0

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*$
answered May 10, 2025 at 19:31

Comments

-2

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

answered Feb 12, 2017 at 21:08

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.