Why we use (?<!…) instead of (?!…) while matching a pattern which should not be preceded by a specific pattern?
Lets see through example. We have two strings below ,
Out First is Hello World. How is it?
Out First is Hi World. How is it?
I want to get only the word ‘World‘ if it is not preceded by ‘Hello‘. So as per our criteria the next string should be matched.
If we use (?<!…), the regex will be:
(?<!Hello\s)World
Output:
Out First is Hello World. How is it?
Out First is Hi World. How is it?
Regex Explanation:
(?<!: Represents negative lookbehind. It ensures to match World when Hello does not occurs before World.
Hello: Represents the word Hello which should not be the prefix of World.
\s : Matches any whitespace character like space, tab, newline etc.
): Represents ending of the negative lookbehind.
World: Represents the actual word to match.
If we use (?!…), the regex will be:
(?!Hello\s)World
Output:
Out First is Hello World. How is it?
Out First is Hi World. How is it?
Regex Explanation:
(?!: Represents negative lookahead.
Hello: Represents the word Hello which should not be the prefix of World.
\s : Matches any whitespace character like space, tab, newline etc.
): Represents ending of the negative lookbehind.
World: Represents the actual word to match.
So for this case (?<! matches our criteria.