[Python] Find each regular expression match and its position

Created on November 30, 2026

re.finditer() yields non-overlapping match objects in order. This example finds ID- followed by digits and prints the text and position of each match.

import re

text = "ID-12, ID-345"

for match in re.finditer(r"ID-\d+", text):
    print(match.group(), match.span())
ID-12 (0, 5)
ID-345 (7, 13)

group() returns the matched text. span() returns zero-based start and end offsets. The end is exclusive, so text[7:13] returns ID-345. If there are no matches, the loop never runs.

References

Python