Python Glossary Русский

all Python 3refunction

(?P<name>...)

groups

A named capturing group. It lets you reach the match by name, through match.group('name') or match['name'], instead of by a numeric index.

Syntax

(?P<name>pattern)
match.group('name')
match.groupdict()

Naming a group does not replace its number: the same group is still m.group(1), it is referenced inside the pattern as (?P=name) and inside an re.sub replacement as \g<name>. The name must be a valid identifier and unique within the pattern — two (?P<x>...) groups in one regex simply fail to compile. groupdict() reports named groups only, and a named group that did not take part in the match maps to None, not to an empty string.

Examples

import re
pattern = r'(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})'
m = re.match(pattern, '2024-06-17')
print(m.group('year'))   # 2024
print(m['month'])        # 06
print(m.groupdict())     # {'year': '2024', 'month': '06', 'day': '17'}

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy