Skip to main content

Foundations of Regular Expressions

Match Objects Deep Dive

0:00
LearnStep 1/3

Match Object Attributes

The Match Object: Your Window into Regex Results

When a regex function like re.search() or re.match() successfully finds a pattern, it doesn't just return True; it returns a Match object. This object is a rich container holding all the information about the match, including the specific substrings captured by groups.

Extracting Content with group()

The primary method for retrieving matched content is .group(). It accepts an index to specify which capture group you want:

  • group(0) (or simply group()): Returns the entire string that matched the pattern.
  • group(1), group(2), etc.: Returns the content of the corresponding parenthesized capturing group.
python

Retrieving All Groups

To get all captured subgroups at once, use .groups(). It returns a tuple containing strings for all subgroups, starting from group 1. It does not include the full match (group 0).

python

Named Groups with groupdict()

If you use named groups in your regex (syntax (?P<name>...)), the .groupdict() method becomes incredibly useful. It returns a dictionary mapping group names to their matched strings.

python