Negative lookbehind

Negative lookbehind matches the string which is definitely not preceded by the pattern which we have defined in the regex pattern part.

Let's see an example to understand the negative lookbehind:

  • Consider the sentence: I play on the playground. It is the best ground.
  • Now you want to extract ground only if it is not preceded by the string play. In this case, you can use negative lookbehind.

The syntax of negative lookbehind is (?<!pattern)

The regex r(?<!play)ground matches ground, but only if it is not preceded by play.

You can see the code snippet which is an implementation of advanceregex() in Figure 4.17:

Figure 4.17: Advanced regex code snippet

The output of the code snippet of Figure 4.17 is given in Figure 4.18:

Figure 4.18: Output of code snippet of advanced regex