Python Glossary Русский

all Python 3refunction

re.Match.group()

groups

Return the text of a single captured group of a Match object: group(0) (or group()) is the whole match, group(n) is the n-th group.

Syntax

m.group(n=0)

The usual failure happens before the call itself: re.match and re.search return None when nothing matches, so .group() then raises AttributeError: 'NoneType' object has no attribute 'group' — check the result first. Groups are numbered by their opening parentheses, nested ones counted alongside the outer ones, and a group that did not participate in the match (say, one guarded by ?) gives None rather than an empty string.

Examples

import re
m = re.match(r'(\w+)@(\w+)', 'user@host')
m.group() # → 'user@host'
m.group(1) # → 'user'
m.group(2) # → 'host'

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy