PYnative

Practice Coding

  • Python ▼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises ▼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQs▼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilers▼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » RegEx » Python Regex Capturing Groups

Python Regex Capturing Groups

Updated on: December 4, 2026 | 3 Comments

In this article, you will learn how to capture regex groups in Python. Capturing groups let you match several distinct parts of a pattern in the same target string and extract each part separately.

Also, Solve:

  • Python Regex Exercises

Table of contents

  • What is a group in regex?
  • Example: Capture multiple groups
    • Access each group result separately
  • Capture a group multiple times
    • findall() with groups
  • Extract a range of group matches
  • Named groups
  • Non-capturing groups
  • Optional groups and default values
  • Backreferences
  • Summary

What is a group in regex?

A group is a part of a regex pattern enclosed in parentheses (). For example, the regular expression (cat) creates a single group containing the letters ‘c’, ‘a’, and ‘t’.

Groups do two jobs:

  • Capture: The text matched by each group is saved, so you can extract it from the Match object. For example, one group can capture a username and another can capture a domain from an email address.
  • Treat several characters as one unit: A quantifier after a group applies to the whole group. For example, (ab)+ matches “ab”, “abab”, “ababab”, and so on.

Groups are numbered by counting their opening parentheses from left to right. For example, the expression ((\w)(\s\d)) contains three groups:

  1. ((\w)(\s\d))
  2. (\w)
  3. (\s\d)
import re

m = re.search(r"((\w)(\s\d))", "a 1")
print(m.group(1))
print(m.group(2))
print(m.group(3))Code language: Python (python)

Output:

a 1
a
 1

Note:

Anything in parentheses () is a capturing group (unless it starts with ?:, see non-capturing groups). Use the group(group_number) method of the Match object to get the text matched by each group.

Example: Capture multiple groups

Suppose you have the following string:

target_string = "The price of PINEAPPLE ice cream is 20"Code language: Python (python)

You want to extract two values from it: the uppercase word (PINEAPPLE) and the number (20). For that, you need two group patterns.

Group 1: an uppercase word: \b[A-Z]+\b

  • [A-Z] is a character class that matches any capital letter from A to Z.
  • The + metacharacter means one or more of them.
  • \b is a word boundary, so the match must be a whole word. Without it, “T” in “The” would match.

Group 2: a number: \d+

  • \d matches any digit from 0 to 9.
  • + means the number has one or more digits.

Between the two groups we put .+. The dot matches any character except a newline, and + repeats it, so .+ skips over the text between the word and the number (” ice cream is “). This part is not in parentheses, so it is matched but not captured.

import re

target_string = "The price of PINEAPPLE ice cream is 20"

# two groups, each enclosed in its own parentheses
result = re.search(r"(\b[A-Z]+\b).+(\b\d+)", target_string)

# all groups as a tuple
print(result.groups())

# each group separately
print(result.group(1))
print(result.group(2))Code language: Python (python)

Output:

('PINEAPPLE', '20')
PINEAPPLE
20
  • We used a raw string (r"...") for the pattern so that Python does not treat backslashes such as \b as escape sequences.
  • The parentheses are not part of the text being matched. They only mark the groups.
  • re.search() returns the first match, and its groups() method returns all captured groups as a tuple.

Access each group result separately

Pass a group number to group() to get the text matched by that group. Unlike string indexing, group numbering starts at 1.

Group 0 is special: it is the entire match (not the entire target string). Calling group() with no argument is the same as group(0).

import re

target_string = "The price of PINEAPPLE ice cream is 20"
result = re.search(r"(\b[A-Z]+\b).+(\b\d+)", target_string)

print(result.group(1))   # first group
print(result.group(2))   # second group
print(result.group(0))   # entire match
print(result.group())    # same as group(0)Code language: Python (python)

Output:

PINEAPPLE
20
PINEAPPLE ice cream is 20
PINEAPPLE ice cream is 20

Asking for a group number that doesn’t exist, such as result.group(3) here, raises IndexError: no such group.

Capture a group multiple times

re.search() returns only the first match. If the string contains several matches and you want the groups of every one, use the finditer() method. It returns an iterator of Match objects, and you can call group() on each one.

import re

target_string = "Ice cream prices: PINEAPPLE 20 MANGO 30 CHOCOLATE 40"

# group 1: an uppercase word, group 2: the number after it
pattern = re.compile(r"(\b[A-Z]+\b)\s(\d+)")

for match in pattern.finditer(target_string):
    print(match.group(1), "->", match.group(2))Code language: Python (python)

Output:

PINEAPPLE -> 20
MANGO -> 30
CHOCOLATE -> 40

findall() with groups

findall() also works with groups, but it returns plain strings and tuples instead of Match objects, so you can’t call group() on the result. Its behavior depends on the number of groups:

  • No groups: a list of the full matches.
  • One group: a list of that group’s matches only.
  • Two or more groups: a list of tuples, one tuple per match.
import re

target_string = "Ice cream prices: PINEAPPLE 20 MANGO 30 CHOCOLATE 40"

print(re.findall(r"\b[A-Z]+\b\s\d+", target_string))      # no groups
print(re.findall(r"\b[A-Z]+\b\s(\d+)", target_string))    # one group
print(re.findall(r"(\b[A-Z]+\b)\s(\d+)", target_string))  # two groupsCode language: Python (python)

Output:

['PINEAPPLE 20', 'MANGO 30', 'CHOCOLATE 40']
['20', '30', '40']
[('PINEAPPLE', '20'), ('MANGO', '30'), ('CHOCOLATE', '40')]

Extract a range of group matches

You can pass several group numbers to group() to get those groups back as a tuple. For example, group(1, 3) returns groups 1 and 3.

import re

target_string = "Jessa, 28, Data Engineer, Berlin"
result = re.search(r"(\w+), (\d+), ([\w ]+), (\w+)", target_string)

print(result.group(1, 2))
print(result.group(1, 3, 4))Code language: Python (python)

Output:

('Jessa', '28')
('Jessa', 'Data Engineer', 'Berlin')

Named groups

Group numbers are hard to read in long patterns and break when you add a new group. Instead, you can give a group a name with the syntax (?P<name>...) and access it by that name.

  • match.group("name") returns the text of one named group.
  • match["name"] is a shortcut for the same thing.
  • match.groupdict() returns all named groups as a dictionary.
import re

email = "jessa.watson@example.com"
m = re.search(r"(?P<user>[\w.]+)@(?P<domain>[\w.]+)", email)

print(m.group("user"))
print(m["domain"])
print(m.groupdict())
print(m.group(1))   # named groups still have numbersCode language: Python (python)

Output:

jessa.watson
example.com
{'user': 'jessa.watson', 'domain': 'example.com'}
jessa.watson

Non-capturing groups

Sometimes you need parentheses only to group a part of the pattern, for example to apply a quantifier or alternation (|), but you don’t want to capture it. Use (?:...) for a non-capturing group. It groups like normal parentheses but doesn’t create a group number, which keeps groups() and findall() results clean.

import re

text = "Prices: 20 USD, 35 EUR, 50 INR"

# capturing group around the currency: findall returns only the currency
print(re.findall(r"\d+ (USD|EUR)", text))

# non-capturing group: findall returns the full match
print(re.findall(r"\d+ (?:USD|EUR)", text))Code language: Python (python)

Output:

['USD', 'EUR']
['20 USD', '35 EUR']

Optional groups and default values

If a group is optional (followed by ?) and doesn’t take part in the match, group() returns None for it. Pass a default value to groups() or groupdict() to use something else instead of None.

import re

# the version suffix after the hyphen is optional
pattern = re.compile(r"(\d+)\.(\d+)(?:-(\w+))?")

m = pattern.search("Release 3.12")
print(m.groups())
print(m.groups(default="stable"))Code language: Python (python)

Output:

('3', '12', None)
('3', '12', 'stable')

Backreferences

A captured group can be reused later in the same pattern. \1 refers to the text matched by group 1, \2 to group 2, and so on. For a named group, use (?P=name). This is useful for finding repeated text.

Example: Find words that are accidentally repeated

import re

text = "This is is a test of the the regex"
print(re.findall(r"\b(\w+) \1\b", text))

# fix the repetition with re.sub(), using \1 in the replacement
print(re.sub(r"\b(\w+) \1\b", r"\1", text))Code language: Python (python)

Output:

['is', 'the']
This is a test of the regex

Learn more about using groups in replacements in Python regex replace using re.sub().

Summary

  • Parentheses () create a capturing group. Groups are numbered from 1, by their opening parenthesis, from left to right.
  • group(n) returns one group, group(0) or group() returns the entire match, and groups() returns all groups as a tuple.
  • Use finditer() to get the groups of every match. findall() returns tuples when the pattern has more than one group.
  • (?P<name>...) creates a named group, and groupdict() returns all named groups.
  • (?:...) groups without capturing.
  • \1 (or (?P=name)) matches the same text that a group already captured.

Previous:

Python Regex Replace

Next:

Regex Metacharacters

Filed Under: Python, Python RegEx

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python RegEx

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
In: Python Python RegEx
TweetF  sharein  shareP  Pin

  Python RegEx

  • Python RegEx
  • Python regex compile
  • Python regex match
  • Python regex search
  • Python regex findall
  • Python regex split
  • Python regex replace
  • Python regex capturing groups
  • Regex Metacharacters
  • Regex special sequences
  • Regex Flags
  • Python Regex Exercises

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com