← Python lessons

Python Regex Groups and re.sub: Capture and Replace

A group is part of a regex inside round brackets. It captures one piece of a match, such as the day in a date. re.sub() replaces every match with new text.

Read Character classes and anchors first.

Capture parts of a match with groups

Put round brackets around each part you want to keep.

import re

match = re.search(r"(\d+)-(\d+)", "Final score 3-2 after extra time")
print(match.group())
print(match.group(1))
print(match.group(2))
print(match.groups())

match.group() is the whole match. group(1) is the first bracket, counting from the left. groups() gives every group as a tuple.

Get tuples from re.findall

When a pattern has two or more groups, re.findall() returns a list of tuples, one per match. Each tuple holds the groups, not the whole match.

import re

settings = "width=80, height=24, depth=3"
pairs = re.findall(r"(\w+)=(\d+)", settings)
print(pairs)
for key, value in pairs:
    print(key, int(value) * 2)

Each tuple unpacks into key and value, like any other pair.

Name your groups

(?P<name>...) gives a group a name. Read it back with match["name"], so you do not need to count brackets.

import re

pattern = r"(?P<day>\d+)/(?P<month>\d+)/(?P<year>\d{4})"
match = re.search(pattern, "Due 25/12/2026")
print(match["year"])
print(match.groupdict())

groupdict() returns every named group in a dictionary.

Replace matches with re.sub

re.sub(pattern, new, text) returns a new string with every match replaced. The original string does not change.

import re

print(re.sub(r"\d", "#", "PIN 4821, card 9917"))
print(re.sub(r"\s+", " ", "too    many   spaces"))

Use groups in the replacement

In the new text, \1 stands for group 1, \2 for group 2, and so on. Write the new text as a raw string too.

import re

dates = "Due 25/12/2026, then 03/01/2027"
print(re.sub(r"(\d+)/(\d+)/(\d+)", r"\3-\2-\1", dates))

Each date is rebuilt with its groups in a new order: year, month, day.

Note: A named group goes in the new text as \g<name>, such as r"\g<year>".

See also: Regex basics, String methods.

Your turn

The names are written Last, First. Print them as First Last, using re.sub() with two groups.

import re

names = "Lovelace, Ada; Turing, Alan"
# add one line: print re.sub() with two groups, putting them back in the other order

Expected output

Ada Lovelace; Alan Turing

Practise this in the free Python course, where every exercise checks your code instantly.