Content · Programming · Python

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

Extract the whole regex match or a particular capture group.

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

Extract the whole regex match or a particular capture group.

How It Works


Match.group(0) returns the whole match, while group(1) or group("name") returns a captured part. Referencing an absent group raises IndexError, and optional unmatched groups may return None.

Step-by-Step Example


import re
matched_token = re.search(r'(?P<prefix>[A-Z]+)-(\d+)', 'AB-42')
print(matched_token.group(0))
print(matched_token.group('prefix'))
print(matched_token.group(2))

Understanding the Example


  • The expression "re.search(r'(?P<prefix>[A-Z]+)-(\\d+)', 'AB-42')" supplies the value stored as 'matched_token'. 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:

AB-42
AB
42

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


Validate the match before reading its groups.

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


  • Calling group() on None or confusing the entire match with the first capture group.
  • Extract a two-part product identifier using numbered and named groups.

Key Takeaways


  • Extract the whole regex match or a particular capture group.
  • Match.group(0) returns the whole match, while group(1) or group("name") returns a captured part.
  • 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.