Groups: pulling out the parts
🌍 In real life. In Bangladesh and India, dates are written day first: 06/10/2026. A database wants 2026-10-06. Finding the date is easy now, but you also need its parts, so you can put them back in a different order.
Round brackets in a pattern make a group: the part it matches is remembered on its own. Step by step:
(\d\d)/(\d\d)/(\d{4})has three groups, numbered 1, 2, 3 by their opening bracket- after
m = re.search(...),m.group(1)is the first group, andm.groups()gives them all as a tuple (m.group(0)orm.group()is the whole match) - a named group
(?P<year>\d{4})can be read asm.group("year"), andm.groupdict()gives a dict of them all - in
re.sub, the replacement can use the groups:\1for group 1, or\g<year>by name
The idea in one sentence: round brackets in a pattern make groups, so a match can hand back its parts (m.group(1)), findall gives the groups, and re.sub can rearrange them with \1, \2, \3.
Its words:
- group:
(\d{2}), a part of the pattern you want back on its own m.group(n)/m.groups(): one part, or all of them as a tuplere.sub(pattern, replacement, text): replace every match\1in a replacement: "whatever group 1 matched"
import re
m = re.search(r"(\d\d)/(\d\d)/(\d{4})", "paid on 06/10/2026")
print(m.group())
print(m.group(1), m.group(2), m.group(3))
print(m.groups())
t = re.search(r"(?P<hour>\d\d):(?P<minute>\d\d)", "train at 09:45")
print(t.group("hour"), t.groupdict())findall and groups. When a pattern has groups, findall gives back just the groups: one string each with one group, or a tuple for each match with several. Each group's letters get their own coloured bar in the scanner.
Rearranging with sub. re.sub(pattern, replacement, text) swaps every match for the replacement, and gives back the new text. Write the replacement as a raw string too, so \3 reaches re as "group 3". Watch each date's groups move into their new places:
import re
marks = "Mina: 92, Rafi: 85, Tara: 78"
pairs = re.findall(r"(\w+): (\d+)", marks)
print(pairs)
print({name: int(score) for name, score in pairs})
print(re.sub(r"(?P<first>\w+) (?P<last>\w+)", r"\g<last>, \g<first>", "Mina Rahman"))Why groups? Finding a date is half the job; you usually need its day, month and year separately. Groups give you the parts without any extra slicing, and sub can rebuild them in any order in one line.
Mistakes and edge cases.
- Group 0.
m.group(0)(orm.group()) is the whole match; the first bracket is group 1. - findall changing shape. With groups, findall gives tuples (or the one group), not the whole matches.
- A replacement without r. In
"\3-\2-\1", Python turns\1into a strange character beforeresees it; writer"\3-\2-\1". - Asking for a group that isn't there.
m.group(4)on a 3-group pattern givesIndexError: no such group.
Quiz
What does this print?
import re m = re.search(r"(\d+)-(\d+)", "pages 10-25") print(m.group(2))What does this print?
import re print(re.findall(r"(\w+)=(\d+)", "a=1 b=22"))What does this print?
import re print(re.sub(r"(\w+) (\w+)", r"\2 \1", "Mina Rahman"))What does this print?
import re m = re.search(r"(?P<h>\d\d):(?P<m>\d\d)", "at 09:45") print(m.group("m"))After
m = re.search(r"(\d+)kg", "bag 25kg"), what ism.group(0)?- '25kg', the whole match
- '25', the first group
- An error: groups start at 1
This should print the year, 2026, but it prints the day. Which line has the mistake?
import re m = re.search(r"(\d{2})/(\d{2})/(\d{4})", "06/10/2026") print(m.group(1))
Coding tasks
Write
to_iso(text: str) -> strwithre.sub: rewrite every day/month/year date like06/10/2026as2026-10-06, leaving the rest of the text as it is.Write
scores(text: str) -> dict[str, int]: turn text like"Mina: 92, Rafi: 85"into{"Mina": 92, "Rafi": 85}.Write
parse_time(text: str) -> tuple[int, int] | Nonewith named groups: the first time like09:45in the text as(9, 45), orNoneif there is no time.