liveBook · Manning

Regex grouping

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

A capture group is a parenthesized subpattern in a regular expression whose matched text is retained for later retrieval.

A capture group is a parenthesized part of a regular expression whose matched text remains available after a successful match. Python retrieves captured values with match.groups() or match.group(number), numbering groups from 1. section 14.1.3

Use capture groups to preserve the pieces your pattern needs later:

  • Split a word into leading consonants and the remaining text: ([consonants]+)?(.+) produces ('ch', 'air') for 'chair' and (None, 'apple') for 'apple'. section 14.1.3
  • Capture a reusable character, such as ([yY]) in ([yY])ou, then combine group 1 with "'all" to preserve capitalization. section 15.1.5
  • Wrap a re.split() separator in capturing parentheses to retain the separators, then use a quantifier such as + to keep adjacent punctuation together. section 15.1.4
  • Use (?:...) when grouping is needed for structure or optionality but the subgroup itself should not receive a capture number. section 16.1.2

Extracting the parts of a word

>>> match = re.match(f'([{consonants}]+)?(.+)', 'chair') >>> match.groups() ('ch', 'air') >>> match.group(1) 'ch' >>> match.group(2) 'air' The first group is optional, so a vowel-starting word can still match; an unmatched optional group returns None. section 14.1.3

>>> match = re.match(f'([{consonants}]+)(.+)', 'chair')
>>> match.groups()
('ch', 'air')

Inspect the runnable two-group match and its tuple of captured values. section 14.1.3

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Explains group retrieval, numbering, optionality, nesting, and non-capturing syntax through runnable examples.
Examples
Demonstrates consonant-vowel word parsing, capitalization-preserving transformations, captured separators, and optional nested patterns.
What it assumes
Assumes basic regular-expression patterns while teaching parentheses, group numbering, and retrieval from match results.
What you can do after
Apply it via Python's re module to extract, reuse, or preserve selected portions of matched text.
How it connects
Connects capture groups with regular expressions, match objects, re.match(), re.search(), re.split(), optional groups, and non-capturing 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 Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.