Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I need to construct a regular expression using language {0,1}

The regular expression should accept odd number of 0's and odd number of 1's

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
361 views
Welcome To Ask or Share your Answers For Others

1 Answer

The whole regex:

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

A way of conceptualizing it:

x = (00|11)
y = (10|01)
z = x*yx*yx*

^(z|x)*y(z|x)*$

Because we are thinking about parity, and not counting, this can be done in regex. The pattern x does not effect parity, while the pattern y switches parity. The pattern z looks for matching y (net effect of zero on parity), ignoring intervening x. Then you just need one y.

Perhaps a shorter regex, using y to match the last switch of parity, may be:

^(z|x)*yx*$
^(x*yx*yx*|x)*yx*

Which is:

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

This has not been tested extensively, but I believe it works.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...