Lessons · Regex · findall hands back the group, not the match
findall hands back the group
Once a pattern has groups, findall returns the groups rather than the match: one tuple per match with more than one group, a plain list with exactly one.
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
Adding brackets to a working findall -- often just to apply a quantifier -- silently changes the shape of the answer.
How to think about it
If the brackets are there for precedence and not to capture, make them (?:...) and findall goes back to handing you the match.
Worked example
re.findall(r'(\w)(\d)', 'a1 b2')Two groups, so a tuple each.
re.findall(r'\w\d', 'a1 b2')No groups, so the matches themselves.
re.findall(r'(ab)+', 'ababab')The match really is ababab, but a repeated group keeps only its LAST repetition.
re.findall(r'(?:ab)+', 'ababab')Non-capturing, so the match comes back whole.
Your turn
Get the whole repeated match rather than the group.
re.findall(r'(ab)+', 'ababab')
Test a pattern against real text
The trap
A group inside a quantifier is overwritten on every repetition. What you get back is the last one, not all of them.
Practise findall hands back the group, not the match on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.