Lessons · Regex · finditer: matches and where they were
The matches, and where they were
finditer hands back a match object per occurrence, each knowing its own position; findall hands back strings and throws the positions away.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Highlighting, slicing around a match, reporting a line number: all of them need to know WHERE, and findall cannot tell you.
How to think about it
Ask whether the position matters. If it does not, findall is shorter. If it does, or if the text is large, finditer is the one that does not build a list first.
Worked example
[m.start() for m in re.finditer(r'a', 'banana')]b0 a1 n2 a3 n4 a5.
re.findall(r'a', 'banana')The same three matches with the positions gone.
[m.span() for m in re.finditer(r'an', 'banana')]It carries on from the END of the last match, so these do not overlap.
Your turn
Collect the position of every 'a' in 'banana'.
[m.start() for m in re.(r'a', 'banana')]
Test a pattern against real text
The trap
Neither of them reports overlapping matches. The engine resumes after the match it just made, not one character along.