Python 3D Academyবাংলা

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:

  1. (\d\d)/(\d\d)/(\d{4}) has three groups, numbered 1, 2, 3 by their opening bracket
  2. after m = re.search(...), m.group(1) is the first group, and m.groups() gives them all as a tuple (m.group(0) or m.group() is the whole match)
  3. a named group (?P<year>\d{4}) can be read as m.group("year"), and m.groupdict() gives a dict of them all
  4. in re.sub, the replacement can use the groups: \1 for 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 tuple
  • re.sub(pattern, replacement, text): replace every match
  • \1 in 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) (or m.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 \1 into a strange character before re sees it; write r"\3-\2-\1".
  • Asking for a group that isn't there. m.group(4) on a 3-group pattern gives IndexError: no such group.

Quiz

  1. What does this print?

    import re
    
    m = re.search(r"(\d+)-(\d+)", "pages 10-25")
    print(m.group(2))
  2. What does this print?

    import re
    
    print(re.findall(r"(\w+)=(\d+)", "a=1 b=22"))
  3. What does this print?

    import re
    
    print(re.sub(r"(\w+) (\w+)", r"\2 \1", "Mina Rahman"))
  4. 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"))
  5. After m = re.search(r"(\d+)kg", "bag 25kg"), what is m.group(0)?

    • '25kg', the whole match
    • '25', the first group
    • An error: groups start at 1
  6. 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

  1. Write to_iso(text: str) -> str with re.sub: rewrite every day/month/year date like 06/10/2026 as 2026-10-06, leaving the rest of the text as it is.

  2. Write scores(text: str) -> dict[str, int]: turn text like "Mina: 92, Rafi: 85" into {"Mina": 92, "Rafi": 85}.

  3. Write parse_time(text: str) -> tuple[int, int] | None with named groups: the first time like 09:45 in the text as (9, 45), or None if there is no time.