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?
Well, this is probably homework, but what the heck:
^(00|11|(01|10)(00|11)*(01|10))*$
Edit: simplified!
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?
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.
@tmp = $str =~ /0/g;
print scalar @tmp % 2 == 0 ? 'even' : 'odd';
精彩评论