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']

Of course, it is much simpler to use an ordinary regular expression that matches foo and then invert the result of the match to ignore strings that contain foo. For example, consider the following straightforward solution:

matches = [s for s in strings if not re.search('foo', s)]

This example produces the same result as the earlier example but with less complexity. However, there are situations where, as a user of certain software tool, we might not have control over how the tool applies the regular expression. Some tools only allow us to provide a pattern, and they automatically select strings that match it. In such cases, if we need to select strings that do not match a given pattern, negative lookahead assertions become quite useful, provided the regular expression flavour supported by the tool allows the use of negative lookahead assertions.

Comments | #python | #programming | #technology