1

I have a task for regexp to recognize 'right' codes:

010101
0101010
1111111
000000

This is example of 'not right' codes:

0110
001
11101
01

I wrote regexp:

^(?:([01])(?!\1))+$|^([01])\2*$

It works.. but I don't understand why :) I can't understand this part:

(?:([01])(?!\1))+

If this ([01]) is '1-st capturing group', then this (?!\1) is not what we get in first capturing in 1-st capturing group. But why it doesn't recognize this(it's right behavior, but why?):

012

? I mean, 2 is not 0, that's what I expect from (?!\1)

  • The `(?!\1)` looks ahead to see that whatever was in group 1 is _not_ in front of it. –  Mar 27 '19 at 18:43
  • 1
    The `^([01])\2*$` takes whatever it found in group 2 and finds it 0 or more times til EOS. –  Mar 27 '19 at 18:44
  • 1
    It won't match `012` because the `2` is not consumed before EOS. Only `[01]` is consumed. Remember, `(?!\1)` is just a condition. It is satisfied by a million characters, but it doesn't consume anything. –  Mar 27 '19 at 18:46
  • @sln thank you a lot! you are wonderful! –  Mar 27 '19 at 18:55

0 Answers0