
Positive Lookahead –
In regular expression, positive lookahead only matches a string if the string followed by a specific pattern.
syntax –
(?=lookahead_regex)
let’s look at one example. Let’s say you want to match with love if it is only followed by python but not with other programming languages or words.
In [1]: import re
In [2]: re.findall('love(?=\spython)', 'I love java')
Out[2]: []
In [3]: re.findall('love(?=\spython)', 'I love dogs')
Out[3]: []
In [4]: re.findall('love(?=\spython)', 'I love python')
Out[4]: ['love']
Negative Lookahead –
In regular expression, Negative lookahead only matches a string if the string is not followed by a specific pattern.
syntax –
(?!lookahead_regex)
Let’s say we only want to match with love if it is not followed by python.
In [5]: re.findall('love(?!\spython)', 'I love java')
Out[5]: ['love']
In [6]: re.findall('love(?!\spython)', 'I love dogs')
Out[6]: ['love']
In [7]: re.findall('love(?!\spython)', 'I love python')
Out[7]: []