re.finditer
findall with the full story: each item is a Match, so you keep the positions, every group and groupdict() — and matches are produced one at a time. Also available as Pattern.finditer(string, pos, endpos).
Demo
import re [(m.group(), m.span()) for m in re.finditer('\\w+', 'to be or not')]
span() is (start, end) with end exclusive, so text[start:end] is the match. With a pattern that can match nothing, like -*, you also get empty matches: one before a, the '--' run, then empty matches before b and at the end. A named group that did not participate shows as None in groupdict() — unlike findall, which would give ''.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| pattern | str | re.Pattern | yes | The regular expression, as a raw string. |
| string | str | yes | The text to scan. |
| flags | re.RegexFlag | int | no (0) | Flags such as re.IGNORECASE. Not allowed with a compiled pattern. |
Return value
Iterator[re.Match] — A lazy iterator yielding one Match object per match, left to right.
Common patterns
import re out, last = [], 0 for m in re.finditer(r'\d+', text): out.append(text[last:m.start()]) out.append(f'[{m.group()}]') last = m.end() out.append(text[last:]) result = ''.join(out)
import re LINE = re.compile(r'(?P<level>[A-Z]+) (?P<msg>.*)') records = [m.groupdict() for m in LINE.finditer(log_text)]
import re from itertools import islice first_three = [m.group() for m in islice(re.finditer(r'\w+', huge_text), 3)]
Examples
Pitfalls
import re ms = re.finditer(r'\d', 'a1b2') first = [m.group() for m in ms] [m.group() for m in ms]
import re ms = list(re.finditer(r'\d', 'a1b2')) first = [m.group() for m in ms] [m.group() for m in ms]
import re type(re.finditer(r'\d', 'a1')).__name__
import re list(re.finditer(r'\d', 'a1'))
When to use
- You need positions (start, end, span) of each match
- Named groups per match — groupdict() records
- Large inputs where you may stop early (lazy)
- Just the strings → re.findall is shorter
- Only the first match → re.search
Notes
FAQ
findall returns a list of strings (or group tuples); finditer returns an iterator of Match objects. Use finditer when you need positions, named groups, or to avoid building a big list.