7.18. Regex Named Group

  • Catch expression results

  • (?P<mygroup>...) - named group mygroup

7.18.1. SetUp

import re

7.18.2. Named Group

  • (?P<mygroup>...) - named group

  • Used when you want to extract specific information from a text

TEXT = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'

year = r'(?P<year>\d{4})'
month = r'(?P<month>[A-Z][a-z]+)'
day = r'(?P<day>\d{1,2})'

date = f'{month} {day}st, {year}'
result = re.search(date, TEXT)

result.group(0)
'Jan 1st, 2000'

result.group(1)
'Jan'

result.group(2)
'1'

result.group(3)
'2000'

result.groups()
('Jan', '1', '2000')

result.group('month')
'Jan'

result.group('day')
'1'

result.group('year')
'2000'

result.groupdict()
{'month': 'Jan', 'day': '1', 'year': '2000'}

7.18.3. Case Study 1

import re

TEXT = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'

result = re.search(r'[A-Z][a-z]+ \d{1,2}st, \d{4}', TEXT)

print(result.groups())
# ()
import re

TEXT = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'

result = re.search(r'([A-Z][a-z]+) (\d{1,2})st, (\d{4})', TEXT)

print(result.groups())
# ('Jan', '1', '2000')

result.group()
# 'Jan 1st, 2000'
result.group(0)
# 'Jan 1st, 2000'
result.group(1)
# 'Jan'
result.group(2)
# '1'
result.group(3)
# '2000'

7.18.4. Case Study 2

import re

TEXT = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'

year = r'(?P<year>\d{4})'
day = r'(?P<day>\d{1,2})'
month = r'(?P<month>[A-Z][a-z]+)'
date = f'{month} {day}st, {year}'

result = re.search(date, TEXT)

result.group()
# 'Jan 1st, 2000'

result.groups()
# ('Jan', '1', '2000')


# st - first
# nd - second
# rd - third
# th - forth
import re

TEXT = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'

year = r'(?P<year>\d{4})'
day = r'(?P<day>\d{1,2})'
month = r'(?P<month>[A-Z][a-z]+)'
date = f'{month} {day}st|nd|rd|th, {year}'

result = re.search(date, TEXT)

result.group()
# 'st'

result.groups()
# (None, None, None)

# st - first
# nd - second
# rd - third
# th - forth
import re

TEXT = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'

year = r'(?P<year>\d{4})'
day = r'(?P<day>\d{1,2})'
month = r'(?P<month>[A-Z][a-z]+)'
date = f'{month} {day}(st|nd|rd|th), {year}'

result = re.search(date, TEXT)

result.group()
# 'Jan 1st, 2000'

result.groups()
# ('Jan', '1', 'st', '2000')

# st - first
# nd - second
# rd - third
# th - forth
import re

TEXT = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'

year = r'(?P<year>\d{4})'
day = r'(?P<day>\d{1,2})'
month = r'(?P<month>[A-Z][a-z]+)'
date = f'{month} {day}(?:st|nd|rd|th), {year}'

result = re.search(date, TEXT)

result.group()
# 'Jan 1st, 2000'

result.groups()
# ('Jan', '1', '2000')

# st - first
# nd - second
# rd - third
# th - forth

7.18.5. Use Case - 1

  • Dates

import re
TEXT = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'
year = r'(?P<year>\d{4})'
month = r'(?P<month>\w{3})'
day = r'(?P<day>\d{1,2}(?:st|nd|rd|th)+?)'
date = f'{month} {day}, {year}'

re.search(date, TEXT).groupdict()
{'month': 'Jan', 'day': '1st', 'year': '2000'}

7.18.6. Use Case - 2

import re


variable = r'(?P<variable>\w+)'
space = r'\s?'  # optional space
value = r'(?P<value>.+)'
assignment = f'^{variable}{space}={space}{value}$'

line_of_code = 'myvar = 123'
re.findall(assignment, line_of_code)
[('myvar', '123')]

7.18.7. Assignments

# %% About
# - Name: RE Syntax PositionalGroup
# - Difficulty: easy
# - Lines: 1
# - Minutes: 3

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Define `result: str` with regular expression pattern to find
#    all years, months, days using named groups (year, month, day)
#    example: [('July', '21', '1969'), ('July', '21', '1969')]
# 2. Define only regex pattern (str), not re.findall(...)
# 3. For simplicity, all ordinals (st, th, nd, rd) were removed
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result: str` z wzorcem wyrażenia regularnego aby wyszukać
#    wszystkich lat, miesięcy, dni używając grup nazwanych (year, month, day)
#    przykład: [('July', '21', '1969'), ('July', '21', '1969')]
# 2. Zdefiniuj tylko wzorzec regex (str), nie re.findall(...)
# 3. Dla uproszczenia, usunięto liczebniki porządkowe (st, th, nd, rd)
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% References
# [1] Authors: Wikipedia contributors
#     Title: Apollo 11
#     Publisher: Wikipedia
#     Year: 2019
#     Retrieved: 2019-12-14
#     URL: https://en.wikipedia.org/wiki/Apollo_11

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from pprint import pprint

>>> matches = re.finditer(result, DATA)
>>> assert matches is not None, \
'Invalid pattern, check if you used positional groups'

>>> match = next(matches)
>>> match.group('month')
'July'
>>> match.group('day')
'20'
>>> match.group('year')
'1969'

>>> match = next(matches)
>>> match.group('month')
'July'
>>> match.group('day')
'21'
>>> match.group('year')
'1969'
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% Imports
import re

# %% Types
result: str

# %% Data
DATA = """Apollo 11 was the American spaceflight that first landed
humans on the Moon. Commander (CDR) Neil Armstrong and lunar module
pilot (LMP) Buzz Aldrin landed the Apollo Lunar Module (LM) Eagle on
July 20, 1969 at 20:17 UTC, and Armstrong became the first person
to step (EVA) onto the Moon's surface (EVA) 6 hours 39 minutes later,
on July 21, 1969 at 02:56:15 UTC. Aldrin joined him 19 minutes later.
They spent 2 hours 31 minutes exploring the site they had named
Tranquility Base upon landing. Armstrong and Aldrin collected 47.5 pounds
(21.5 kg) of lunar material to bring back to Earth as pilot Michael Collins
(CMP) flew the Command Module (CM) Columbia in lunar orbit, and were on the
Moon's surface for 21 hours 36 minutes before lifting off to rejoin
Columbia."""

# %% Result
result = r''

# %% About
# - Name: RE Syntax Group
# - Difficulty: easy
# - Lines: 1
# - Minutes: 2

# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author

# %% English
# 1. Define `result: str` with regular expression pattern to find
#    all durations using named group
#    example: [{'hours': '6', 'minutes': '39'}, {'hours': '2', 'minutes': '31'}]
# 2. Define only regex pattern (str), not re.findall(...)
# 3. Ignore durations without hours (only with minutes)
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result: str` z wzorcem wyrażenia regularnego aby wyszukać
#    wszystkie okresy czasowe używając grupy nazwanej
#    przykład: [{'hours': '6', 'minutes': '39'}, {'hours': '2', 'minutes': '31'}]
# 2. Zdefiniuj tylko wzorzec regex (str), nie re.findall(...)
# 3. ZIGNORUJ okresy bez godzin (tylko z minutami)
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% References
# [1] Authors: Wikipedia contributors
#     Title: Apollo 11
#     Publisher: Wikipedia
#     Year: 2019
#     Retrieved: 2019-12-14
#     URL: https://en.wikipedia.org/wiki/Apollo_11

# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'

>>> from pprint import pprint

>>> result = [x.groupdict() for x in re.finditer(result, DATA)]
>>> pprint(result, compact=True, width=50)
[{'hours': '6', 'minutes': '39'},
 {'hours': '2', 'minutes': '31'},
 {'hours': '21', 'minutes': '36'}]
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`

# %% Imports
import re

# %% Types
result: str

# %% Data
DATA = """Apollo 11 was the American spaceflight that first landed
humans on the Moon. Commander (CDR) Neil Armstrong and lunar module
pilot (LMP) Buzz Aldrin landed the Apollo Lunar Module (LM) Eagle on
July 20th, 1969 at 20:17 UTC, and Armstrong became the first person
to step (EVA) onto the Moon's surface (EVA) 6 hours 39 minutes later,
on July 21st, 1969 at 02:56:15 UTC. Aldrin joined him 19 minutes later.
They spent 2 hours 31 minutes exploring the site they had named
Tranquility Base upon landing. Armstrong and Aldrin collected 47.5 pounds
(21.5 kg) of lunar material to bring back to Earth as pilot Michael Collins
(CMP) flew the Command Module (CM) Columbia in lunar orbit, and were on the
Moon's surface for 21 hours 36 minutes before lifting off to rejoin
Columbia."""

# %% Result
result = r''