Negative Lookahead Assertion
By Susam Pal on 20 Nov 2024
Here is an example of negative lookahead assertion in regular expression using Python:
import re
strings = ['foo', 'bar', 'baz', 'foo-bar', 'bar-baz', 'baz-foo']
matches = [s for s in strings if re.search('^(?!.*foo)', s)]
print(matches)
The regular expression ^(?!.*foo)
in the above example
matches strings that do not contain the pattern foo
.
The above code example produces the following output:
['bar', 'baz', 'bar-baz']
See docs.python.org/3/library/re.html for more details on various lookahead assertions.