Assert Context with Lookaround
Core idea
Lookaround tests nearby text without consuming it. (?=...) and (?!...) assert positive and negative lookahead. (?<=...) and (?<!...) assert lookbehind. Python re requires a fixed-width lookbehind pattern.
import reprint(re.findall(r"[0-9]+(?=kg)", "12kg 8m 5kg"))The unit is required by the assertion but excluded from the matches.
Inspect a preceding marker
import reprint(re.findall(r"(?<=#)[0-9]+", "#42 8 #7"))The fixed-width # prefix is checked without being consumed.
Common mistake
A variable-length lookbehind such as (?<=a+) is invalid in re. Consider a consuming group followed by extraction instead.
Practice
Extract numeric text following # without including #. Try inputs with and without a marker.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Lookaround
Check your understanding of lookaround.
What is printed?
import reprint(re.findall(r"[0-9]+(?=m)","7m 9s"))What is printed?
import reprint(re.findall(r"(?<=@)[A-Z]","A @B"))Which syntax asserts that the next text does not match?
Which constraint applies to Python re lookbehind?