liveBook · Manning

Group

As explained in Python How-To

A group method is a regular-expression match operation that returns the substring captured by specified groups or the complete match when no group number is supplied.

Need to retrieve text from a regular-expression match? Call group() on the Match object. With no argument, it returns the complete match; with a number, it returns that capturing group. section 2.4.4

Retrieve the complete match and individual groups

A pattern containing two capturing groups lets you retrieve the entire match with group(0), or each captured value with group(1) and group(2): match = re.match(r"(\w+), (\w+)", "Homework, urgent; today") match.group(0) # 'Homework, urgent' match.group(1) # 'Homework' match.group(2) # 'urgent'

Use numbered groups when the pattern is small and stable. For structured records, group(1), group(2), and group(3) can extract fields such as an ID, title, and description, but counting positions becomes error-prone as patterns grow. section 2.5.2

Prefer named groups for maintainable patterns: define names with (?P<name>pattern), then pass those names to group(). When dictionary-style processing fits better, groupdict() returns the named captures. section 2.5.3

How Python How-To covers it

How deep it goes
Explains complete, numbered, and named retrieval through worked examples, while warning that positional numbering becomes error-prone.
Examples
Demonstrates extracting words from a phrase and task IDs, titles, and descriptions from structured text.
What it assumes
Assumes regular-expression patterns and Match objects, while introducing capture groups and their retrieval methods.
What you can do after
Apply Python's regular-expression Match API to retrieve complete, numbered, or named captured text.
How it connects
Connects regular expressions with Match objects, capturing groups, named groups, and groupdict().

Also explained in

Compare how 2 books explain group →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.