7.17. Regex Positional Group

  • Catch expression results

  • (...) - unnamed (positional) group

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

7.17.1. SetUp

>>> import re

7.17.2. Problem

  • string = 'Hello Alice'

  • r'Hello \w+' - matches entire string, but does not capture Alice

>>> string = 'Hello Alice'
>>>
>>> re.findall(r'Hello \w+', string)
['Hello Alice']

7.17.3. One Group

  • string = 'Hello Alice'

  • r'Hello (\w+)' - capture Alice

>>> string = 'Hello Alice'
>>>
>>> re.findall(r'Hello (\w+)', string)
['Alice']

7.17.4. Many Groups

  • string = 'Hello Alice Apricot'

  • r'Hello (\w+) (\w+)' - capture Alice and Apricot

>>> string = 'Hello Alice Apricot'
>>>
>>> re.findall(r'Hello (\w+) (\w+)', string)
[('Alice', 'Apricot')]

7.17.6. Case Study 1

>>> email = 'alice@example.com'
>>>
>>>
>>> re.findall(r'[a-z]+@example.com', email)
['alice@example.com']
>>>
>>> re.findall(r'([a-z]+)@example.com', email)
['alice']
>>>
>>> re.findall(r'([a-z]+)@([a-z.]+)', email)
[('alice', 'example.com')]
>>>
>>> re.findall(r'([a-z]+)@([a-z]+)\.([a-z]+)', email)
[('alice', 'example', 'com')]

7.17.7. Case Study 2

>>> import re
>>>
>>> string = 'Email from Alice Apricot <alice@example.com> received on: Jan 1st, 2000 at 12:00AM'

Case 1 - Without Positional Groups:

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

Case 2 - With Positional Groups:

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

7.17.8. Use Case - 1

>>> html = '<p>Hello World</p>'
>>>
>>>
>>> re.findall(r'<.+>', html)
['<p>Hello World</p>']
>>>
>>> re.findall(r'<.+?>', html)
['<p>', '</p>']
>>>
>>> re.findall(r'<(.+?)>', html)
['p', '/p']

7.17.9. Use Case - 2

>>> string = 'Email from Alice Apricot <alice@example.com> received on: Jan 1st, 2000 at 12:00AM'
>>>
>>> year = r'(?P<year>\d{4})'
>>> month = r'(?P<month>[A-Z][a-z]+)'
>>> day = r'(?P<day>\d{1,2})'
>>>
>>> pattern = f'{month} {day}st, {year}'
>>> result = re.search(pattern, string)
>>>
>>> result.group(0)
'Jan 1st, 2000'
>>>
>>> result.group(1)
'Jan'
>>>
>>> result.group(2)
'1'
>>>
>>> result.group(3)
'2000'
>>>
>>> result.groups()
('Jan', '1', '2000')

7.17.10. Assignments

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

# %% 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 positional groups
#    example: [('July', '21', '1969'), ('July', '21', '1969')]
# 2. Define only regex pattern (str), not re.findall(...)
# 3. For simplicity, the regular expression pattern was already given,
#    now you need to add positional groups to it
# 4. For simplicity, all ordinals (st, th, nd, rd) were removed from the text
# 5. 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 pozycyjnych
#    przykład: [('July', '21', '1969'), ('July', '21', '1969')]
# 2. Zdefiniuj tylko wzorzec regex (str), nie re.findall(...)
# 3. Dla uproszczenia, podano już wzorzec wyrażenia regularnego,
#    teraz należy dodać do niego grupy pozycyjne
# 4. Dla uproszczenia, z tekstu usunięto liczebniki porządkowe (st, th, nd, rd)
# 5. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# >>> match = next(matches)
# >>> match.group(1)
# 'July'
# >>> match.group(2)
# '21'
# >>> match.group(3)
# '1969'

# %% 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 has an is invalid version; expected: `3.9` or newer.'

>>> 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(1)
'July'
>>> match.group(2)
'20'
>>> match.group(3)
'1969'

>>> match = next(matches)
>>> match.group(1)
'July'
>>> match.group(2)
'21'
>>> match.group(3)
'1969'
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -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'[A-Z][a-z]+ \d{1,2}, \d{4}'

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

# %% 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 positional group
#    example: [('6', '39'), ('2', '31'), ('21', '36')]
# 2. Define only regex pattern (str), not re.findall(...)
# 3. For simplicity, the regular expression pattern was already given,
#    now you need to add positional groups to it
# 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 pozycyjnej
#    przykład: [('6', '39'), ('2', '31'), ('21', '36')]
# 2. Zdefiniuj tylko wzorzec regex (str), nie re.findall(...)
# 3. Dla uproszczenia, podano już wzorzec wyrażenia regularnego,
#    teraz należy dodać do niego grupy pozycyjne
# 4. Uruchom doctesty - wszystkie muszą się powieść

# %% Expected
# >>> result
# [('6', '39'),
#  ('2', '31'),
#  ('21', '36')]

# %% 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 has an is invalid version; expected: `3.9` or newer.'

>>> from pprint import pprint

>>> result = re.findall(result, DATA)
>>> pprint(result, compact=True, width=20)
[('6', '39'),
 ('2', '31'),
 ('21', '36')]
"""

# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -f -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'\d+ hours \d+ minutes'