Use finditer() to inspect each matched substring and its original position.
How It Works
findall() is useful for values, but finditer() returns Match objects with start(), end() and group(). Offsets are zero-based and the end position is exclusive. This is particularly helpful when highlighting terms in source text.
An empty-width pattern can also produce matches; plan for zero-length results when designing replacements.
Step-by-Step Example
import re
text = "Order 12 and order 35"
for match in re.finditer(r"\d+", text):
print(match.group(), match.start(), match.end())
Understanding the Example
- The expression '"Order 12 and order 35"' supplies the value stored as 'text'. 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:
12 6 8
35 19 21
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
Highlight the matches by slicing the original string from start to end.
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
- Assuming Match.end() is the index of the last included character instead of the first index after the match.
- Using findall() and then searching again for positions, which can confuse repeated values.
Key Takeaways
- Use finditer() to inspect each matched substring and its original position.
- findall() is useful for values, but finditer() returns Match objects with start(), end() and group().
- An empty-width pattern can also produce matches; plan for zero-length results when designing replacements.