re.Match
One successful match. Its repr shows the span and the text; methods (group, groups, groupdict, start, end, span, expand) read the parts, and a handful of attributes describe how the search was run. It is always truthy — failure is None, not an empty Match.
Demo
import re m = re.search('(?P<num>\\d+)|(?P<word>[a-z]+)', ' hello 42') (m.lastindex, m.lastgroup, m.regs)
In the alternation case only the word branch matched, so lastindex is 2 and lastgroup is word; group 1 shows (-1, -1) in regs. For ((a)(b)) the outer group 1 closes last, so lastindex is 1 even though groups 2 and 3 matched. A failed search returns None, and reading .lastindex on it raises AttributeError. endpos is clamped to len(string).
Attributes
| Attribute | Type | Meaning |
|---|---|---|
| pos | int | The pos passed to search()/match() — where scanning started (0 by default) |
| endpos | int | The endpos passed — the scan limit (len(string) by default) |
| lastindex | int | None | Number of the last group that was closed during the match; None if no group matched |
| lastgroup | str | None | Name of that last closed group; None if it has no name or no group matched |
| re | re.Pattern | The compiled pattern that produced this match |
| string | str | The string that was searched (the whole string, not just the match) |
| regs | tuple | Undocumented: ((start, end), …) for group 0 and every group, (-1, -1) when unmatched — the same as span(i) for each i |
Common patterns
import re def first_number(text): m = re.search(r'\d+', text) if m is None: return None return int(m.group())
import re TOKEN = re.compile(r'(?P<NUM>\d+)|(?P<NAME>[A-Za-z_]\w*)|(?P<OP>[-+*/=])|(?P<WS>\s+)') tokens = [(m.lastgroup, m.group()) for m in TOKEN.finditer(src) if m.lastgroup != 'WS']
import re def first_word(text: str) -> re.Match[str] | None: return re.search(r"\w+", text)
Examples
Pitfalls
import re re.match(r'((a)(b))', 'ab').lastindex
import re m = re.match(r'((a)(b))', 'ab') sum(g is not None for g in m.groups())
import re text = 'x' * 1000 + '42' m = re.search(r'\d+', text) len(m.string)
import re text = 'x' * 1000 + '42' found = re.search(r'\d+', text).group() len(found)
When to use
- Getting positions, groups and the pattern behind a result
- Dispatching on which named alternative matched (lastgroup)
- Testing for "empty match" with bool(m) — a Match is always True; compare m.group() == ''
- regs in new code — it is undocumented; use span(i)
Notes
FAQ
The object search, match and fullmatch return on success (and finditer yields). It holds the matched text, its position and every group — its repr looks like <re.Match object; span=(6, 8), match='66'>.