Negative look-behind is a type of lookaround construct in regular expressions that matches a pattern only if it is not preceded by another pattern, without including the first pattern in the match.
In Python's re module, the syntax for negative look-behind is (?<!pattern), where pattern is the pattern that must not precede the match. For example, the regular expression (?<!foo)bar would match the string "bar" only if it is not preceded by the string "foo".
Here's an example:
import retext = "The bar is preceded by foo, but not by baz."pattern = r"(?<!foo)bar"matches = re.findall(pattern, text)print(matches) |
In this example, the regular expression (?<!foo)bar matches the string "bar" only if it is not preceded by the string "foo". The re.findall() function finds all non-overlapping matches of the pattern in the input string text.
The output of this program is:
['bar', 'bar'] |
Notice that the regular expression matches both occurrences of "bar", because neither one is preceded by "foo".
Negative look-behind constructs are useful when you want to match a pattern only if it is not preceded by another pattern, without including that pattern in the match. They can be very powerful tools for building complex regular expressions.
Note that the negative lookbehind assertion (?<!...) must also be of fixed width, meaning that the length of the pattern must be a fixed number of characters.