SyntaxStudy
Sign Up
Python Lookahead and Lookbehind
Python Advanced 5 min read

Lookahead and Lookbehind

Lookahead and Lookbehind

Zero-width assertions that match based on surrounding context without consuming characters. Positive lookahead: (?=...). Negative: (?!...). Lookbehind: (?<=...).

Example
import re

text = "100px 200em 300px"
# Find numbers followed by "px"
matches = re.findall(r"\d+(?=px)", text)
print(matches)  # ["100", "300"]

# Find numbers NOT followed by "px"
matches2 = re.findall(r"\d+(?!px)", text)
print(matches2)  # ["200"]
Pro Tip

Lookbehind assertions must be fixed-width in Python.