Look-ahead is a type of lookaround construct in regular expressions that allows you to match a pattern only if it is followed by another pattern, without including the second pattern in the match.
In Python's re module, the syntax for positive look-ahead is (?=pattern), where pattern is the pattern that must follow the match. For example, the regular expression foo(?=bar) would match the string "foo" only if it is followed by the string "bar".
Here's an example:
import retext = "The foo is followed by bar, 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 "foo" only if it is 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 followed by "bar".
Negative look-ahead is also possible using the syntax (?!pattern). This matches a pattern only if it is not followed by another pattern. For example, the regular expression foo(?!bar) would match the string "foo" only if it is not followed by the string "bar".
Look-ahead constructs are useful when you want to match a pattern only if it is followed by or not followed by another pattern, without including that pattern in the match. They can be very powerful tools for building complex regular expressions.