liveBook · Manning

Regex grouping

As explained in Python How-To

A capturing group is a delimited subexpression in a regular expression whose matched substring is retained for later access.

A capturing group is a parenthesized part of a regular-expression pattern whose matched text can be retrieved separately. Group 0 is the full match; numbered groups correspond to the parenthesized parts. section 2.4.4

match = re.match(r"(\w+), (\w+)", "Homework, urgent; today")
print(match)
# output: <re.Match object; span=(0, 16), match='Homework, urgent'>

match.groups()
# output: ('Homework', 'urgent')

match.group(0)
# output: 'Homework, urgent'

match.group(1)
# output: 'Homework'

match.group(2)
# output: 'urgent'

This example separates “Homework” and “urgent” from the full match using numbered groups. section 2.4.4

Groups can capture separate fields, such as an ID, title, and description, for later processing. Numbering many groups can be error-prone; named groups make the captured data clearer and easier to refer to. section 2.5.2 section 2.5.4

How Python How-To covers it

How deep it goes
Explains parentheses, group numbering, and retrieval; flags numbering risks but does not detail named-group mechanics.
Examples
Uses a comma-separated phrase and task records with ID, title, and description fields.
What you can do after
Apply Python regular-expression matching to extract separate fields from text.
How it connects
Connects capturing groups to regular expressions, Match objects, and named groups.

Also explained in

Compare how 6 books explain regex grouping →

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.