user3011417
user3011417

Reputation: 21

Regular Expression (consecutive 1s and 0s)

Hey I'm supposed to develop a regular expression for a binary string that has no consecutive 0s and no consecutive 1s. However this question is proving quite tricky. I'm not quite sure how to approach it as is.

If anyone could help that'd be great! This is new to me.

Upvotes: 0

Views: 8089

Answers (1)

paxdiablo
paxdiablo

Reputation: 881363

You're basically looking for alternating digits, the string:

...01010101010101...

but one that doesn't go infinitely in either direction.

That would be an optional 0 followed by any number of 10 sets followed by an optional 1:

^0?(10)*1?$

The (10)* (group) gives you as many of the alternating digits as you need and the optional edge characters allow you to start/stop with a half-group.

Keep in mind that also allows an empty string which may not be what you want, though you could argue that's still a binary string with no consecutive identical digits. If you need it to have a length of at least one, you can do that with a more complicated "or" regex like:

^(0(10)*1?)|(1(01)*0?)$

which makes the first digit (either 1 or 0) non-optional and adjusts the following sequences accordingly for the two cases.

But a simpler solution may be better if it's allowed - just ensure it has a length greater than zero before doing the regex check.

Upvotes: 5

Related Questions