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
