Regexp for exceptions 101 and 110

What is a regular expression that accepts everything in {0,1} but does not have substring 110 or 101?

Accept:

  • 111111
  • 000011111
  • 100001000001001
  • 010
  • 1

Reject

  • 100110
  • 010100
  • 123

Edit: In the comments on the answers below, this question requires formal regular expression.

+3
source share
6 answers

Limited to the formal designation of regular expressions:

((1|0*|0*1)(000*))*0*(10*|1*)
+3
source

This solution (even without viewing):

/^0*(11*$|10$|100+)*$/
  • Start with any number of zeros.
  • Loop (I know: the line processed so far does not end with "1" or "10")
    • "$ 1" in order (& stop)
    • "11", , , .
    • "10 $" .
    • "10" , . .
+11

, /101|110/

+6

, , , , regex lookahead.

/^(1(?!01|10)|0)*$/
+4

:

/^([01])\1*$/
-1

DFA .

, "" ( "", "xor", "not", )

,

(0 | 100 | (1 | 10 | 11 *) $) *

This can be solved with a possessive comparison. (111 + $) is 111 ++

-1
source

Source: https://habr.com/ru/post/1722259/


All Articles