Regular expression to match string of 0's and 1's without '011' substring

17,823

Solution 1

Automata diagram Edit: Updated to include start states and fixes, as per below comments.

Solution 2

If you are looking for all strings that do not have 011 as a substring rather than simply excluding the string 011:

A classic regex for that would be:

1*(0+01)*

Basically you can have as many ones at the beginning as you want, but as soon as you hit a zero, it's either zeros, or zero-ones that follow (since otherwise you'd get a zero-one-one).

A modern, not-really-regular regex would be:

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

IF, however, you want any string that is not 011, you can simply enumerate short string and wildcard the rest:

λ+0+1+00+01+10+11+(1+00+010)(0+1)*

And in modern regex:

^(?!011)[01]*$
Share:
17,823
Prasoon Saurav
Author by

Prasoon Saurav

About me Software engineer at a stealth startup. 22nd C gold badge recipient. 62nd C++ gold badge recipient. Contacts prasoonsaurav.nit @ gmail prasoonsaurav @ linkedin prasoon @ codementor

Updated on June 22, 2022

Comments

  • Prasoon Saurav
    Prasoon Saurav almost 2 years

    I'm working on a problem (from Introduction to Automata Theory, Languages and Computer by Hopcroft, Motwani and Ullman) to write a regular expression that defines a language consisting of all strings of 0s and 1s not containing the substring 011.

    Is the answer (0+1)* - 011 correct ? If not what should be the correct answer for this?