liveBook · Manning

Named capturing group

As explained in The Quick Python Book, Fourth Edition

A named capturing group is a capturing group assigned an identifier that can be used to retrieve its matched text.

A named capturing group assigns an identifier to a regular-expression subpattern, making its matched text retrievable by name instead of by numeric position. Python uses the syntax (?P<name>...). section 16.4

Use named groups with these practical rules:

  • Wrap each value to extract in parentheses and give it a unique name, such as (?P<last>...). section 16.4
  • After search succeeds, call result.group('name') to retrieve the corresponding match. section 16.4
  • Treat an optional named group as potentially absent: a successful overall match can still produce None for that group. section 16.4
  • Do not confuse ?P<name>, which names a group, with ? in an optional pattern; they serve different purposes. section 16.4

Extracting a contact record

A pattern can name last, first, middle, and phone fields. After regexp.search(line), retrieve them with result.group('last'), result.group('first'), result.group('middle'), and result.group('phone'); replace a missing middle value with an empty string. section 16.4

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains naming syntax, match retrieval, optional-group behavior, and the distinction between two question-mark uses.
Examples
Demonstrates parsing names and phone numbers from lines using a compiled pattern and named group lookups.
What it assumes
Assumes regular-expression familiarity while introducing named subpattern syntax and match-object extraction.
What you can do after
Apply named groups to extract readable fields from matched Python strings.
How it connects
Links regular expressions with capturing groups, optional patterns, match objects, and search operations.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.