3

How do I write a regular expression for binary strings such that it's length is a multiple of 3 and this must include the empty string. So for example 010 is true 0101 is false.

0

3 Answers 3

7

Wrap your regex inside the ^ $ so that it performs matching over the whole string.

^([01]{3})*$
Sign up to request clarification or add additional context in comments.

1 Comment

Nice and compact, I have been noticing and like your regex style. Upvoting. :)
4

The following should work:

^(?:[01]{3})*$

Edit: non-capture group for optimization.

Comments

3

Here is what I would suggest:

^(?:[01]{3})*$

It matches the pattern you need, but does not capture the group which is taken into the brackets.

Explanation:

^ // matches beginning of the string
    (?: // opens a non-capturing group
        [01] // a symbol class, which could only contain 0's or 1's
        {3} // repeat exactly three times
    ) // closes the previously opened group
    * // repeat [0, infinity] times
$ // matches the end of the string

Comments

Your Answer

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.