What is the difference between (?=) and (?<=) in regex?
(?=) is used to check if a string (which we want to match) is followed by another string or not.
(?<=) is used to check if a string (which we want to match) is preceded by another string or not.
Let’s see an example for (?=) first.
We have a line Hello World
. And we want to match Hello if it is followed by World .
Regex will be
Hello(?=\sWorld)
Output :
Hello World
Pattern Explanation :
Hello : Actual string to match.
(?= : Represents the starting of positive lookahead.
\s : Matches any whitespace character like space, tab, newline etc.
World : Matches the string which should be followed by Hello.
) : Represents ending of the positive lookahead.
If we use (?<=) in place of (?=) here, it will not match Hello .
If we wanted to match World which is preceded by Hello then we could use (?<=)
Then regex will be
(?<=Hello\s)World
Output :
Hello World
Pattern Explanation :
(?<= : Starting of Positive Lookbehind.
Hello : String that should be preceded by.
\s : Matches any whitespace character like space, tab, newline etc.
) : Ending of Positive Lookbehind.
World : Actual string to match.
We can not use (?=) instead of (?<=) here for matching World which is preceded by Hello .