Grouping and Capturing

2 min read ·

Grouping allows you to extract specific parts of a matched pattern using parentheses. It is very useful when you want to work with different sections of a string.

Using ()

Parentheses are used to create groups in regex.
This captures the number from the string.

Multiple Groups

You can define multiple groups in a single pattern.
Output:
  • John
  • 25

Accessing Groups

  • group() returns full match
  • group(1) returns first group
  • group(2) returns second group

Using Multiple Matches


Note

Grouping helps in extracting structured data like names, numbers, and patterns.


Practical Example


Pro Tip

Use grouping when you need specific parts of matched data instead of full string.


Important Points

  • () creates groups
  • Multiple groups can be used
  • group() helps access data
  • Works well with structured patterns

Caution

If pattern does not match, group() will raise an error, so always check result before accessing.


Exercise

  • Extract name and age from string
  • Extract date using grouping
  • Use finditer() with groups
  • Print each group separately