Use lookahead and lookbehind to inspect context without consuming it.
How It Works
Assertions such as (?=...) and (?<=...) test surrounding text while keeping it outside the match. Traditional Python lookbehind requires a fixed-width pattern; complicated variable-length lookbehind often needs a different design.
Step-by-Step Example
import re
message = 'USD 25, EUR 30'
amounts = re.findall(r'(?<=USD )\d+', message)
print(amounts)
print(re.findall(r'\d+(?=,)', message))
Understanding the Example
- The expression "'USD 25, EUR 30'" supplies the value stored as 'message'. This value is then used or checked by the later statements.
- The expression "re.findall(r'(?<=USD )\\d+', message)" supplies the value stored as 'amounts'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
['25']
['25']
Where This Fits in a Real Program
Start by writing down examples that should match and examples that must fail. Check whether you need to locate a substring, match a prefix or validate an entire field; these are different operations. Unicode and escape sequences can also change which characters are matched, so test accented text and empty input.
Practice: Try It Yourself
Use groups when the context must be extracted as well.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Attempting arbitrary variable-width lookbehind or thinking a lookahead becomes part of the match.
- Match numbers only when immediately followed by a percent sign.
Key Takeaways
- Use lookahead and lookbehind to inspect context without consuming it.
- Assertions such as (?=...) and (?<=...) test surrounding text while keeping it outside the match.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.