liveBook · Manning

Match object

As explained in The Quick Python Book, Fourth Edition

A match object is a Python regular-expression result object that records the substring matched and provides access to captured groups and match positions.

A match object records what a Python regular expression matched. A successful `search` returns one; an unsuccessful search returns `None`. Check the result before extracting text from it. section 16.4

Named groups make parts of a match accessible:

  • Name a subpattern with `(?P<name>...)`, then read its matched text with `result.group('name')`. section 16.4
  • An optional group can return `None` even when the overall pattern matches. Check it before using its value as text. section 16.4

Extracting a record

For a record shaped like `surname, firstname middlename: phonenumber`, named groups can separate the names and phone number. If the middle name is absent, `result.group('middle')` is `None`; the required phone group still has matched text. section 16.4

import re
int_string = "1 2 3 4 5"
def int_match_to_float(match_obj):
    return(match_obj.group('num') + ".0")
 
pattern = r"(?P<num>[0-9]+)"
regexp = re.compile(pattern)
regexp.sub(int_match_to_float, int_string)
 
'1.0 2.0 3.0 4.0 5.0'

A replacement function receives each match object from `sub`. Here it reads the named digit group and appends `.0`, turning `1 2 3 4 5` into `1.0 2.0 3.0 4.0 5.0`. section 16.5.1

Match objects can also provide more information, including substring positions; those methods are not detailed here. section 16.7

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains search results, named-group access, optional groups, and substitution callbacks, but leaves position-related methods undetailed.
Examples
Demonstrates extracting names and phone numbers from records and changing matched integers to strings ending in `.0`.
What it assumes
Assumes basic Python strings and functions while introducing named-group extraction and match objects passed to callbacks.
What you can do after
Apply it via Python `re` to inspect named matches and generate replacements from each match.
How it connects
Connects match objects to regular expressions, named capture groups, `search`, and function-based `sub` replacements.

Also explained in

Compare how 2 books explain match object →

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.