re.findall
The quickest way to pull every occurrence out of a text. Read the return type rule first: capturing groups change what you get back. Also available as Pattern.findall(string, pos, endpos).
Demo
import re re.findall('\\d+', 'Order 66 shipped 3 boxes, 120 kg')
The type rule in action: no group gives the whole matches, one group gives just that group's text, two groups give tuples — and (?:...) groups without capturing, so it behaves like no group. An optional group that did not take part becomes '' (not None). Empty matches are included: \d* on 'a1b' yields ['', '1', '', ''] — an empty match before a, the 1, then empty matches before b and at the very end.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| pattern | str | re.Pattern | yes | The regular expression, as a raw string. |
| string | str | yes | The text to scan, left to right. |
| flags | re.RegexFlag | int | no (0) | Flags such as re.IGNORECASE. Not allowed with a compiled pattern. |
Return value
list[str] | list[tuple[str, ...]] — Whole matches (no groups), group 1 (one group), or tuples of all groups (two or more). Unmatched groups give empty strings.
Common patterns
import re numbers = [int(n) for n in re.findall(r'-?\d+', text)]
import re settings = dict(re.findall(r'(\w+)\s*=\s*(\S+)', config_text))
import re word_count = len(re.findall(r'\b\w+\b', text))
Examples
Pitfalls
import re re.findall(r'\w+\.(com|org)', 'a.com b.org')
import re re.findall(r'\w+\.(?:com|org)', 'a.com b.org')
import re re.findall(r'aa', 'aaaa')
import re re.findall(r'(?=(aa))', 'aaaa')
import re re.findall(r'\d+', 'a1 b22')
import re [(m.group(), m.span()) for m in re.finditer(r'\d+', 'a1 b22')]
When to use
- Extracting every occurrence as plain strings (or group tuples)
- Quick counts and dict-building from key/value text
- Need positions or named groups → re.finditer
- Huge text where you stop early → re.finditer (lazy) instead of a full list
- Only the first occurrence → re.search
Notes
FAQ
Your pattern has two or more capturing groups, so each item is a tuple of the groups. With exactly one group you get a list of that group's strings. Replace grouping-only parentheses with (?:...).