0
0
PythonHow-ToBeginner · 3 min read

How to Use Regex Groups in Python: Simple Guide

In Python, you use regex groups by placing parts of your pattern inside parentheses (). You can then access these groups using match.group(n) where n is the group number, starting at 1 for the first group.
📐

Syntax

Regex groups are created by wrapping part of the pattern in parentheses (). The entire match is group 0, and groups inside parentheses are numbered from 1 upwards.

  • pattern = r"(group1)(group2)": defines two groups.
  • match.group(0): returns the full matched text.
  • match.group(1): returns the first group.
  • match.group(2): returns the second group, and so on.
python
import re
pattern = r"(\w+)@(\w+\.\w+)"
text = "contact me at user@example.com"
match = re.search(pattern, text)
if match:
    print(match.group(0))  # full match
    print(match.group(1))  # first group
    print(match.group(2))  # second group
Output
user@example.com user example.com
💻

Example

This example shows how to extract the username and domain from an email using regex groups.

python
import re
pattern = r"(\w+)@(\w+\.\w+)"
text = "Send email to alice@openai.com for info."
match = re.search(pattern, text)
if match:
    username = match.group(1)
    domain = match.group(2)
    print(f"Username: {username}")
    print(f"Domain: {domain}")
Output
Username: alice Domain: openai.com
⚠️

Common Pitfalls

Common mistakes when using regex groups include:

  • Forgetting parentheses, so no groups are created.
  • Using group(0) expecting a group but it returns the full match.
  • Trying to access a group number that does not exist, causing an error.
  • Not checking if match is None before accessing groups.
python
import re
pattern = r"\w+@\w+\.\w+"  # No groups here
text = "email: bob@example.com"
match = re.search(pattern, text)
if match:
    # Wrong: trying to get group(1) when no groups exist
    try:
        print(match.group(1))
    except IndexError:
        print("No group 1 found")

# Correct way with groups
pattern = r"(\w+)@(\w+\.\w+)"
match = re.search(pattern, text)
if match:
    print(match.group(1))  # prints 'bob'
Output
No group 1 found bob
📊

Quick Reference

ConceptDescription
(pattern)Defines a capturing group in regex
group(0)Returns the full matched string
group(1), group(2), ...Return the text matched by the first, second, etc. group
re.search()Finds the first match and returns a match object
match.group(n)Access the nth group from the match object

Key Takeaways

Use parentheses () in regex to create groups for capturing parts of text.
Access groups with match.group(n), where n starts at 1 for the first group.
Always check if the match is not None before accessing groups to avoid errors.
group(0) returns the full matched text, not a group inside parentheses.
Avoid accessing group numbers that do not exist to prevent exceptions.