0

I am studying regex lookaround from this tutorial.

It has an example explaining how lookaround are used to check the existence (or non-existence), but the regex inside lookaround parentheses is not used for actual match.

In example, the pattern q(?=u)i is checked against String quit. And it doesn't return a match.

I understood the example.
But I can't think of any string that matches this regex pattern. If my understanding of lookaround is correct I think there isn't any String that matches with this regex.

Am I correct? If not, which String matches this regex?

narendra-choudhary
  • 4,582
  • 4
  • 38
  • 58

1 Answers1

1

I'm not a big fan of this tutorial site, but if you read closely what it actually says, it never claims that the regex q(?=u)i matches the string quit:

Let's take one more look inside, to make sure you understand the implications of the lookahead. Let's apply q(?=u)i to quit. The lookahead is now positive and is followed by another token. Again, q matches q and u matches u. Again, the match from the lookahead must be discarded, so the engine steps back from i in the string to u. The lookahead was successful, so the engine continues with i. But i cannot match u. So this match attempt fails. All remaining attempts fail as well, because there are no more q's in the string.

I think you might still be confused about how lookaheads work. Either that, or you misread the tutorial site. If the former, then lookaheads work by asserting a match, without actually consuming anything in the string. So the regex q(?=u)i says to:

match the letter 'q'
lookahead to the next character after 'q' and assert that it is 'u'
then match an 'i' immediately after the 'q'

Of course, the string 'quit' fails, and in fact all strings would fail. The lookahead says to verify that q is followed by u, but the following pattern contradicts this by insisting that i is what follows.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • I follow you and I think my language was a little confusing. I've changed question a bit to make things more clear. I'm looking for a string that returns a match on `q(?=u)i`. **quit** doesn't return a match. I could not think of a string that will return a match against this regex. – narendra-choudhary Aug 29 '17 at 05:37
  • 1
    @gitblame I don't think you followed what I said actually. There is _no_ string which will match this regex. Again, the lookahead asserts `qu` while the actual pattern matches `qi`. Obviously, this will always fail for any string. – Tim Biegeleisen Aug 29 '17 at 05:38
  • didn't read last statement of your answer earlier. Understood it now. Thanks. – narendra-choudhary Aug 29 '17 at 06:05
  • @gitblame Lookarounds are possibly the highest barrier of entry to mastering regex, so you can expect for it to take a while to click. – Tim Biegeleisen Aug 29 '17 at 06:12