Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reg Ex for even number of 0s and 1s

Tags:

regex

I am trying to create a regular expression that determines if a string (of any length) matches a regex pattern such that the number of 0s in the string is even, and the number of 1s in the string is even. Can anyone help me determine a regex statement that I could try and use to check the string for this pattern?

like image 673
canton Avatar asked Apr 18 '12 07:04

canton


People also ask

What is a regular expression for a set of strings of 0s and 1s with even number of 0s?

The expression +0+1 describes the strings with length zero or one, and the expression (0 + 1)*(00 + 10 + 11) describes the strings with length two or more. ¯ (c). All strings containing an even number of 0's: 1*+ (1*01*0)*1*.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What is regex a zA Z0 9?

The bracketed characters [a-zA-Z0-9] indicate that the characters being matched are all letters (regardless of case) and numbers. The * (asterisk) following the brackets indicates that the bracketed characters occur 0 or more times.


2 Answers

So completely reformulated my answer to reflect all the changes:

This regex would match all strings with only zeros and ones and only equal amounts of those

^(?=1*(?:01*01*)*$)(?=0*(?:10*10*)*$).*$

See it here on Regexr

I am working here with positive lookahead assertions. The big advantage here of a lookahead assertion is, that it checks the complete string, but without matching it, so both lookaheads start to check the string from the start, but for different assertions.

  1. (?=1*(?:01*01*)*$) does check for an equal amount of 0 (including 0)

  2. (?=0*(?:10*10*)*$) does check for an equal amount of 1 (including 0)

  3. .* does then actually match the string

Those lookaheads checks:

(?=
    1*    # match 0 or more 1
    (?:   # open a non capturing group
        0     # match one 0
        1*    # match 0 or more 1
        0     # match one 0
        1*    # match 0 or more 1
    )
    *     # repeat this pattern at least once
    $     # till the end of the string
)
like image 56
stema Avatar answered Nov 07 '22 10:11

stema


So, I have come up with a solution to the problem:

(11+00+(10+01)(11+00)\*(10+01))\*
like image 23
canton Avatar answered Nov 07 '22 11:11

canton