Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression for strings with an even number of zeroes and ones

Tags:

regex

What is a regular expression for strings of 0 and 1 with an even number of zeros and an even number of ones?

I have something like (1*01*01*)*(0*10*10*)*.

Does it look good?

like image 671
Kevinniceguy Avatar asked Apr 27 '10 22:04

Kevinniceguy


3 Answers

Well, this is probably homework, but what the heck:

^(00|11|(01|10)(00|11)*(01|10))*$

Edit: simplified!

like image 187
tloflin Avatar answered Nov 09 '22 10:11

tloflin


1100 is in the language, but doesn't match your expression. 10101 is not in the language, but your expression matches it.

I'd suggest starting by drawing a DFA. There's a pretty obvious 4-state machine that recognizes this language. (Is it possible to do better?) The empty string is in the language, so the start state is an accepting state. Are there other accepting states? For a non-accepting state S, is there a prefix that takes you from start->S? Is there a way to loop from S back to S without hitting an accepting state? Is there suffix that takes you from S back to an accepting state?

like image 40
Jim Lewis Avatar answered Nov 09 '22 10:11

Jim Lewis


A counterexample for your given regular expression is 01010101.

You may find that writing a regular expression for this particular problem is not going to be possible (unless you use some non-regular extensions to the usual regular expression language).

As mentioned by Jim Lewis below, this should indeed be a solvable problem.

like image 42
Greg Hewgill Avatar answered Nov 09 '22 10:11

Greg Hewgill