ßastian
ßastian

Reputation: 1854

Regex of Binary sequence that does not contains 00

I am trying to get a regular expression that: - Has any sequence of 0 and 1. (Binary only) - And Does not contains 00

I know them separate but how I can combine them?

(?:[0-1]+)+

the above for sequence of 0101 of any kind.

Here is screenshot of the part of the question:

Here is the part of the question

any clue reference would be appreciated.

Upvotes: 0

Views: 2777

Answers (3)

AdrianHHH
AdrianHHH

Reputation: 14038

Regular expressions such as 0?(1+0)* will match against any part of the string so it will match the middle part of a string such as 000011000000, it will match the 0110. To check that the whole string matches need to add the start and end of string anchors, giving ^0?(1+0)*$. This will also match an empty string. To match against a non-empty string we could use ^0?(1+0)+$ but this will not match a string with a single 0. So we need to add an alternative (using |) to match the 0, leading to the total expression ^((0?(1+0?)+)|0)$.

These brackets are capturing brackets, they could be changed to non-capturing forms but that would make the expression bigger and, visually, more complex.

Upvotes: 0

Ibrahim
Ibrahim

Reputation: 6088

You could try something like this:

(10)+|(01)+|1+

Demo: https://regex101.com/r/2CFroT/4

Upvotes: 0

Adam
Adam

Reputation: 5599

I came to this form:

0?(1+0?)*

Explained:

  1. 0? - can start with 0
  2. 1+ - non-empty sequence of 1s
  3. 0? - followed by at most one 0
  4. (1+0?)* - 2-3 repeated any number of times

Upvotes: 1

Related Questions