Positive look-behind is a type of lookaround construct in regular expressions that matches a pattern only if it is preceded by another pattern, including the first pattern in the match.
In Python's re module, the syntax for positive look-behind is (?<=pattern), where pattern is the pattern that must precede the match. For example, the regular expression (?<=foo)bar would match the string "bar" only if it is 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 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'] |
Notice that the regular expression matches only the first occurrence of "bar", because it is preceded by "foo".
Positive look-behind constructs are useful when you want to match a pattern only if it is preceded by another pattern, including that pattern in the match. They can be very powerful tools for building complex regular expressions.
Note that the lookbehind assertion (?<=...) must be of fixed width, meaning that the length of the pattern must be a fixed number of characters.