Lookaheads
Lesson 20 of 28 in Coddy's RegEx in Python course.
Lookaheads are assertions that allow you to match a group of characters only if they are followed (positive lookahead) or not followed (negative lookahead) by a specific pattern. Lookaheads do not consume characters in the string, they only assert whether a match is possible.
- Positive Lookahead
<strong>(?=...)</strong>: Matches a group of characters only if they are followed by a specific pattern. - Negative Lookahead
<strong>(?!...)</strong>: Matches a group of characters only if they are not followed by a specific pattern.
import re
text = "foo1 foo2 foo3 foo"
pattern_positive = r"foo(?=\d)"
pattern_negative = r"foo(?!\d)"
matches_positive = re.findall(pattern_positive, text)
matches_negative = re.findall(pattern_negative, text)
print("Matches with positive lookahead:", matches_positive) # Output: ['foo', 'foo', 'foo']
print("Matches with negative lookahead:", matches_negative) # Output: ['foo']In the above example, the pattern foo(?=\d) matches "foo" only if it is followed by a digit, while the pattern foo(?!\d) matches "foo" only if it is not followed by a digit.
Challenge
EasyWrite a function named find_numbers_followed_by_words that takes a text string as input and returns a list of numbers that are followed by a word.
Try it yourself
import re
def find_numbers_followed_by_words(text):
# Write code hereAll lessons in RegEx in Python
1Introduction
Introduction