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

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

regex - Detect strings having odd number of 0s and 1s

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

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

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...