Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

re.Match.group — retrieving matched groups

The re.Match.group method retrieves the whole match or selected capturing groups by their number or name.

Version: Python 3.14; repository image, production runtime not attested

Syntax

match.group([group1, ...])

re.Match.group operates on a match object. First check that the matching operation did not return None. match.group() and match.group(0) return the whole match, not necessarily the entire input.

Capturing groups are numbered from 1 in opening-parenthesis order. A (?P<name>...) group can be selected by name or number. One argument selects one value; multiple arguments return a tuple in the requested order. Matched values are str or bytes, depending on the input.

A group that did not participate returns None, whereas a group matching an empty string returns an empty string. For a repeated group, only the last capture is available. A negative or out-of-range number, or an unknown name, raises IndexError.

Examples

import re

match = re.fullmatch(r"(?P<item>[a-z]+)(?:-([0-9]+))?", "book")
if match is None:
    raise ValueError("No match")

print(match.group())
print(match.group("item"))
print(match.group(1, 2))

Result

book
book
('book', None)

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources