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





