re.Match
Prev: re.match | Up: re | Next: re.Pattern
Rel: re.compile, re.error, re.escape, re.findall
Ref: docs.python.org — re.Match
Tags: #public #python3 #stdlib #re
Import
import re
from re import Match
Signature & Overview
re.Match()
The result of re.match() and re.search().
Methods & Attributes
Match.end(self, group=0, /)— Return index of the end of the substring matched by group.Match.expand(self, /, template)— Return the string obtained by doing backslash substitution on the string template, as done by the sub() method.Match.group(...)— Return subgroup(s) of the match by indices or names.Match.groupdict(self, /, default=None)— Return a dictionary containing all the named subgroups of the match, keyed by the subgroup name.Match.groups(self, /, default=None)— Return a tuple containing all the subgroups of the match, from 1.Match.span(self, group=0, /)— For match object m, return the 2-tuple (m.start(group), m.end(group)).Match.start(self, group=0, /)— Return index of the start of the substring matched by group.
Usage
import re
m = re.search(r"(?P<user>\w+)@(?P<host>[\w.]+)", "Contact: ada@example.com")
assert isinstance(m, re.Match)
assert m.group(0) == "ada@example.com"
assert m.group("user") == "ada" and m.groupdict() == {"user": "ada", "host": "example.com"}
assert m.span() == (9, 24)
Gotchas
- Not directly instantiable:
Matchobjects are only returned bysearch(),match(),fullmatch(), andfinditer(). - Always check
if m is not None:: Failed matches returnNone, so callingm.group()without checking raisesAttributeError.
REPL Inspect
from re import Match
help(Match)
Linked from
Related notes
- tuts/python3/stdlib_module/re/match Linked here; links to this page; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/Pattern Linked here; links to this page; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/re/compile Linked here; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/error Linked here; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/escape Linked here; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/findall Linked here; shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/finditer shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/fullmatch shared tags: #re, #stdlib
- tuts/python3/stdlib_module/re/PatternError shared tags: #re, #stdlib