Iterate through regex matches with spans and capture groups.
How It Works
re.finditer() yields Match objects lazily. It is useful for large inputs where you need match positions, named groups, or rich match metadata without constructing a large result list.
Step-by-Step Example
import re
message = 'A12 B34'
for match_object in re.finditer(r'[A-Z]\d+', message):
print(match_object.group(), match_object.span())
Understanding the Example
- The expression "'A12 B34'" supplies the value stored as 'message'. This value is then used or checked by the later statements.
- The for loop processes one item per iteration rather than requiring a separate statement for each value.
A successful run of this example prints the following output:
A12 (0, 3)
B34 (4, 7)
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 findall() for a simple list of values when positions are irrelevant.
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
- Trying to access the iterator again after it is exhausted or assuming overlapping matches are returned.
- Highlight each matched number by recording its start and end positions.
Key Takeaways
- Iterate through regex matches with spans and capture groups.
- re.finditer() yields Match objects lazily.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.