Negative look-ahead is a type of lookaround construct in regular expressions that matches a pattern only if it is not followed by another pattern. In other words, it matches a pattern only if the following text does not match a specified pattern.
In Python's re module, the syntax for negative look-ahead is (?!pattern), where pattern is the pattern that must not follow the match. For example, the regular expression foo(?!bar) would match the string "foo" only if it is not followed by the string "bar".
Here's an example:
import retext = "The foo is not followed by bar, but it is followed by baz."pattern = r"foo(?!bar)"matches = re.findall(pattern, text)print(matches) |
In this example, the regular expression foo(?!bar) matches the string "foo" only if it is not followed by the string "bar". The re.findall() function finds all non-overlapping matches of the pattern in the input string text.
The output of this program is:
['foo'] |
Notice that the regular expression matches only the first occurrence of "foo", because it is not followed by "bar".
Negative look-ahead constructs are useful when you want to match a pattern only if it is not followed by another pattern. They can be very powerful tools for building complex regular expressions.