liveBook · Manning

Match object

As explained in Python How-To

A match object represents one regular-expression match and provides information about that match, such as its location.

A match object represents one successful regular-expression match. Create one with re.search() or re.match(); search() scans anywhere, while match() requires the pattern at the string’s beginning. The object exposes the matched text and its location, and evaluates to True in a conditional. section 2.4.4

Use these methods to inspect the match:

  • group() returns the complete matched string; group(n) returns a numbered capturing group. section 2.4.4
  • span() returns the match’s start and end positions; span(n) returns the positions for a specific group. section 2.4.4 section 2.4.5
  • start() and end() return the match boundaries separately, while groups() returns all captured groups as a tuple. section 2.4.4
  • finditer() yields match objects for multiple matches, preserving descriptive information such as each match’s location. section 2.4.5

Inspect a match

match = re.search(r"(\w\d)+", "xyza2b1c3dd") if match: print("matched:", match.group()) print("span:", match.span()) print("start:", match.start(), "end:", match.end()) # matched: a2b1c3 # span: (3, 9) # start: 3 end: 9

Read captured fields

match = re.match(r"(\w+), (\w+)", "Homework, urgent; today") if match: print(match.groups()) print(match.group(0)) print(match.group(1), match.group(2)) # ('Homework', 'urgent') # Homework, urgent # Homework urgent

How Python How-To covers it

How deep it goes
Explains creation, truthiness, core inspection methods, numbered groups, and iteration, without descending into implementation internals.
Examples
Demonstrates matched text and spans, numbered groups, and parsing structured task records.
What it assumes
Assumes basic Python conditionals and regular-expression patterns while demonstrating match creation and group inspection.
What you can do after
Diagnose regular-expression results by testing truthiness and printing matched text, captured groups, and character positions.
How it connects
Connects regular expressions with search, match, capturing groups, findall, and finditer.

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 Python How-To. The section links point to the parts of the book it draws on.