user3011417
user3011417

Reputation: 21

Regex that does not contain the substring 010

I'm trying to write a regex expression to exclude binary strings that contain 010.
I'm not quite sure what to write.

I have this to start with but I'm not too sure what to do:

1*(0+10)*

Thank you!

Upvotes: 0

Views: 5103

Answers (3)

Bohemian
Bohemian

Reputation: 425003

Use an anchored negative look ahead:

^(?!.*010)[01]+$

Upvotes: 0

tripleee
tripleee

Reputation: 189377

Your attempt requires any stretch of zeros to be followed by 10 which is clearly a violation of your constraint. Instead, require any 1 to be followed by at least one more, or end of string.

(0*(1(1+|$))*)*

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 149020

If you want to match binary string (strings which contain only 1's and 0's) but exclude strings which contain the string 010, perhaps use something like this:

^((?!010)[01])*$

This will match any sequence of zero or more 0 or 1 characters such that the sequence does not contain the substring 010. The start (^) and end ($) anchors will ensure that no additional characters are allowed in the input string.

Upvotes: 1

Related Questions