user3037172
user3037172

Reputation: 587

How to match an even number of 1's and any amount of 0's

Im having trouble with this regex problem.

Language is {1,0}.

I want strings with an even number of 1's and any amount of 0's.

Sample strings include:

110
101
11
0
empty set 
1111
10101010101

Upvotes: 6

Views: 102

Answers (1)

dee-see
dee-see

Reputation: 24078

^(0*10*1)*0*$ or ^(?:0*10*1)*0*$ if non-capturing groups are supported by your regex engine.

It could also be further "simplified" to ^((0*1){2})*0*$, whatever you find to be more readable.

This matches 1s by pair and pads with any number of zeros as necessary. It does not match if the number of 1s is odd. It matches the empty line.

It doesn't use anything fancy so it should work in most programming languages.

See it in action on regex101.

Upvotes: 9

Related Questions