Content · Programming · Python

Python re.Match.groups() Method: Usage and Examples

Retrieve all captured groups as a tuple.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Retrieve all captured groups as a tuple.

How It Works


Match.groups(default=None) returns the values of all capture groups, excluding group zero. Optional groups that did not participate are None unless you specify a default value.

Step-by-Step Example


import re
matched_address = re.search(r'(\w+)(?:-(\d+))?', 'room')
print(matched_address.groups())
print(matched_address.groups('missing'))

Understanding the Example


  • The expression "re.search(r'(\\w+)(?:-(\\d+))?', 'room')" supplies the value stored as 'matched_address'. This value is then used or checked by the later statements.
  • The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.

A successful run of this example prints the following output:

('room', None)
('room', 'missing')

Where This Fits in a Real Program


Start by writing down examples that should match and examples that must fail. Check whether you need to locate a substring, match a prefix or validate an entire field; these are different operations. Unicode and escape sequences can also change which characters are matched, so test accented text and empty input.

Practice: Try It Yourself


Use groupdict() when readable named keys are more useful than positions.

For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.

Further Reading


Read the official Python documentation for complete parameters, return types and exceptions.

Common Beginner Mistakes


  • Expecting groups() to include the whole matched string or return a dictionary.
  • Create a pattern with two optional fields and supply a default.

Key Takeaways


  • Retrieve all captured groups as a tuple.
  • Match.groups(default=None) returns the values of all capture groups, excluding group zero.
  • Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.
Share this resourceSend this page to someone who may find it useful.