Search code examples
regexpcreregex-lookaroundscharacter-class

Character class vs. Lookaround - matching non-existing character at the end of a word.


q[^x] – matches “qu” in “question”. It does not match “Iraq” since there is no character after the “q” for the negated character class to match.

q(?!u) matches “q” in “Iraq” but not in “question”. (This is a negative lookahead).

The “there is no character after the ‘q’ for the … to match” does not apply? How this can be explained?

Source:

https://www.regular-expressions.info/quickstart.html

"Character classes or character sets" and "Lookaround".


Solution

  • The negative lookahead asserts (not "matches") that

    There is no u after q

    Is there a u after the q in Iraq? No, so the q matches (not the u though!).

    The reverse character class matches

    a character that is not u after q.

    This implies that there must first be a character after q, and it has to not be u. So Iraq does not match.