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

