Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

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
like image 450
user3037172 Avatar asked Sep 05 '14 13:09

user3037172


1 Answers

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

like image 52
dee-see Avatar answered Nov 12 '22 10:11

dee-see