Lookbehinds
Lesson 21 of 28 in Coddy's RegEx in Python course.
Lookbehinds are assertions that allow you to match a group of characters only if they are preceded (positive lookbehind) or not preceded (negative lookbehind) by a specific pattern. Like lookaheads, lookbehinds do not consume characters in the string.
- Positive Lookbehind
<strong>(?<=...)</strong>: Matches a group of characters only if they are preceded by a specific pattern. - Negative Lookbehind
<strong>(?<!...)</strong>: Matches a group of characters only if they are not preceded by a specific pattern.
import re
text = "1foo 2foo 3foo foo"
pattern_positive = r"(?<=\d)foo"
pattern_negative = r"(?<!\d)foo"
matches_positive = re.findall(pattern_positive, text)
matches_negative = re.findall(pattern_negative, text)
print("Matches with positive lookbehind:", matches_positive) # Output: ['foo']
print("Matches with negative lookbehind:", matches_negative) # Output: ['foo', 'foo', 'foo']In the above example, the pattern (?<=\d)foo matches "foo" only if it is preceded by a digit, while the pattern (?<!\d)foo matches "foo" only if it is not preceded by a digit.
Challenge
EasyWrite a function named find_words_preceded_by_numbers that takes a text string as input and returns a list of words that are preceded by a number.
Try it yourself
import re
def find_words_preceded_by_numbers(text):
# Write code hereAll lessons in RegEx in Python
1Introduction
Introduction