6.8. Regex Syntax Group
Catch expression results
Can be named or positional
(...)
- unnamed group(?P<mygroup>...)
- named group mygroup(?:...)
- non-capturing group(?#...)
- comment
6.8.1. SetUp
>>> import re
6.8.2. Positional Group
(...)
- unnamed (positional) groupUsed when you want to extract specific information from a text
>>> TEXT = 'Email from Mark Watney <mwatney@nasa.gov> received on: Sun, Jan 2nd, 2000 at 12:00 AM'
>>> re.findall(r'\dnd', TEXT)
['2nd']
>>>
>>> re.findall(r'(\d{1,2})nd', TEXT)
['2']
>>>
>>> re.findall(r'\d{1,2}(nd)', TEXT)
['nd']
>>> re.findall(r'(\d{1,2})(nd)', TEXT)
[('2', 'nd')]
>>> re.findall(r'\d{1,2}:\d{2}', TEXT)
['12:00']
>>>
>>> re.findall(r'(\d{1,2}):\d{2}', TEXT)
['12']
>>>
>>> re.findall(r'\d{1,2}:(\d{2})', TEXT)
['00']
>>>
>>> re.findall(r'(\d{1,2}):(\d{2})', TEXT)
[('12', '00')]
>>> re.findall(r'([A-Z][a-z]+\s[A-Z][a-z]+)', TEXT)
['Mark Watney']
>>>
>>> re.findall(r'([A-Z][a-z]+) ([A-Z][a-z]+)', TEXT)
[('Mark', 'Watney')]
>>>
>>> re.findall(r'([A-Z][a-z]+) ([A-Z][a-z]+)', TEXT)[0]
('Mark', 'Watney')
>>> firstname = r'([A-Z][a-z]+)'
>>> lastname = r'([A-Z][a-z]+)'
>>>
>>> re.findall(f'{firstname} {lastname}', TEXT)[0]
('Mark', 'Watney')
>>> firstname = r'([A-Z][a-z]+)'
>>> lastname = r'([A-Z][a-z]+)'
>>> name = f'{firstname} {lastname}'
>>>
>>> re.findall(name, TEXT)[0]
('Mark', 'Watney')
>>> firstname = r'[A-Z][a-z]+'
>>> lastname = r'[A-Z][a-z]+'
>>> name = f'({firstname}) ({lastname})'
>>>
>>> re.findall(name, TEXT)[0]
('Mark', 'Watney')
6.8.3. Named Group
(?P<mygroup>...)
- named groupUsed when you want to extract specific information from a text
>>> TEXT = 'Email from Mark Watney <mwatney@nasa.gov> received on: Sun, Jan 2nd, 2000 at 12:00 AM'
>>> firstname = r'[A-Z][a-z]+'
>>> lastname = r'[A-Z][a-z]+'
>>> name = f'(?P<firstname>{firstname}) (?P<lastname>{lastname})'
>>>
>>> re.findall(name, TEXT)
[('Mark', 'Watney')]
>>>
>>> re.search(name, TEXT)
<re.Match object; span=(11, 22), match='Mark Watney'>
>>>
>>> re.search(name, TEXT).groups()
('Mark', 'Watney')
>>>
>>> re.search(name, TEXT).groupdict()
{'firstname': 'Mark', 'lastname': 'Watney'}
>>> TEXT = 'Email from Mark Watney <mwatney@nasa.gov> received on: Sun, Jan 2nd, 2000 at 12:00 AM'
>>> time = r'(?P<hour>\d{1,2}):(?P<minute>\d{1,2})'
>>>
>>> re.findall(time, TEXT)
[('12', '00')]
>>>
>>> re.search(time, TEXT).groups()
('12', '00')
>>>
>>> re.search(time, TEXT).group(0)
'12:00'
>>>
>>> re.search(time, TEXT).group(1)
'12'
>>>
>>> re.search(time, TEXT).group(2)
'00'
>>>
>>> re.search(time, TEXT).groupdict()
{'hour': '12', 'minute': '00'}
6.8.4. Non-Capturing Group
(?:...)
- non-capturing groupDiscard the group from the results
Used when you want to use parentheses to group a part of the regular expression
>>> TEXT = 'Email from Mark Watney <mwatney@nasa.gov> received on: Sun, Jan 2nd, 2000 at 12:00 AM'
>>> re.findall(r'\w{3} \d{1,2}nd, \d{4}', TEXT)
['Jan 2nd, 2000']
>>>
>>> re.findall(r'\w{3} \d{1,2}st|nd|rd|th, \d{4}', TEXT)
['nd']
>>>
>>> re.findall(r'\w{3} \d{1,2}(st|nd|rd|th), \d{4}', TEXT)
['nd']
>>>
>>> re.findall(r'\w{3} \d{1,2}(?:st|nd|rd|th), \d{4}', TEXT)
['Jan 2nd, 2000']
>>>
>>> re.findall(r'(\w{3}) (\d{1,2})(?:st|nd|rd|th), (\d{4})', TEXT)
[('Jan', '2', '2000')]
>>>
>>> re.findall(r'(\w{3}) (\d{1,2})(st|nd|rd|th), (\d{4})', TEXT)
[('Jan', '2', 'nd', '2000')]
>>> date = r'(\w{3} \d{1,2}(?:st|nd|rd|th), \d{4})'
>>> re.findall(date, TEXT)
['Jan 2nd, 2000']
>>> year = r'\d{4}'
>>> month = r'\w{3}'
>>> day = r'\d{1,2}'
>>>
>>> re.findall(f'{month} {day}(st|nd|rd|th), {year}', TEXT)
['nd']
>>>
>>> re.findall(f'{month} {day}(?:st|nd|rd|th), {year}', TEXT)
['Jan 2nd, 2000']
6.8.5. Comment
(?#...)
- commentComments are ignored by the regex engine
>>> TEXT = 'Email from Mark Watney <mwatney@nasa.gov> received on: Sun, Jan 2nd, 2000 at 12:00 AM'
>>> re.findall(r'\d{4}(?#year)', TEXT)
['2000']
>>>
>>> re.findall(r'\d{1,2}(?#hour):\d{2}(?#minute)', TEXT)
['12:00']
>>> hour = r'\d{1,2}(?#hour)'
>>> minute = r'\d{2}(?#minute)'
>>> time = f'{hour}:{minute}'
>>>
>>> re.findall(time, TEXT)
['12:00']
>>>
>>> time
'\\d{1,2}(?#hour):\\d{2}(?#minute)'
6.8.6. Examples
(\w+)
- word character (including unicode chars, numbers an underscores)\d+(\.\d+)?
- float with optional decimals\d+(,\d+)?
- number with coma (,
) as thousands separator(?P<word>\w+)
- name group word with\w+
with at least one word character (including unicode chars, numbers an underscores)(.+) \1
- matchesthe the
or55 55
(.+) \1
- not matchesthethe
(note the space after the group)
>>> import re
>>> TEXT = 'Email from Mark Watney <mwatney@nasa.gov> received on: Sun, Jan 2nd, 2000 at 12:00 AM'
>>> re.findall(r'\d{,2}(st|nd|rd|th)?', TEXT)
['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', 'nd', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '']
>>>
>>> re.findall(r'\d{1,2}(st|nd|rd|th)?', TEXT)
['nd', '', '', '', '']
>>>
>>> re.findall(r'\d{1,2}(st|nd|rd|th)+?', TEXT)
['nd']
>>>
>>> re.findall(r'\d{1,2}st|nd|rd|th+?', TEXT)
['nd']
>>>
>>> re.findall(r'\d{1,2}(?:st|nd|rd|th)+?', TEXT)
['2nd']
>>>
>>> re.findall(r'(\d{1,2})(st|nd|rd|th)+?', TEXT)
[('2', 'nd')]
>>>
>>> re.findall(r'(\d{1,2})(?:st|nd|rd|th)+?', TEXT)
['2']
>>>
>>> re.findall(r'(\w{3}) (\d{1,2})(?:st|nd|rd|th)+?, (\d{4})', TEXT)
[('Jan', '2', '2000')]
>>>
>>> re.findall(r'(\w{3}) (\d{1,2})(?:st|nd|rd|th)+?, (\d{4})', TEXT)[0]
('Jan', '2', '2000')
>>>
>>> re.findall(r'(\w{3} \d{1,2}(?:st|nd|rd|th)+?, \d{4})', TEXT)
['Jan 2nd, 2000']
6.8.7. Atomic Grouping
Since Python 3.11
Atomic grouping
((?>...))
and possessive quantifiers (*+
,++
,?+
,{m,n}+
) are now supported in regular expressions.
6.8.8. Case Study 1
import re
TEXT = 'Email from Mark Watney <mwatney@nasa.gov> received on: Sun, Jan 2nd, 2000 at 12:00 AM'
result = re.search(r'[A-Z][a-z]+ \d{1,2}nd, \d{4}', TEXT)
print(result.groups())
# ()
import re
TEXT = 'Email from Mark Watney <mwatney@nasa.gov> received on: Sun, Jan 2nd, 2000 at 12:00 AM'
result = re.search(r'([A-Z][a-z]+) (\d{1,2})nd, (\d{4})', TEXT)
print(result.groups())
# ('Jan', '2', '2000')
result.group()
# 'Jan 2nd, 2000'
result.group(0)
# 'Jan 2nd, 2000'
result.group(1)
# 'Jan'
result.group(2)
# '2'
result.group(3)
# '2000'
import re
TEXT = 'Email from Mark Watney <mwatney@nasa.gov> received on: Sun, Jan 2nd, 2000 at 12:00 AM'
result = re.search(r'(?P<month>[A-Z][a-z]+) (?P<day>\d{1,2})nd, (?P<year>\d{4})', TEXT)
print(result.groups())
# ('Jan', '2', '2000')
result.group()
# 'Jan 2nd, 2000'
result.group(0)
# 'Jan 2nd, 2000'
result.group(1)
# 'Jan'
result.group(2)
# '2'
result.group(3)
# '2000'
result.group('year')
# '2000'
result.group('month')
# 'Jan'
result.group('day')
# '2'
result.groupdict()
# {'month': 'Jan', 'day': '2', 'year': '2000'}
import re
TEXT = 'Email from Mark Watney <mwatney@nasa.gov> received on: Sun, Jan 2nd, 2000 at 12:00 AM'
date = r'(?P<month>[A-Z][a-z]+) (?P<day>\d{1,2})nd, (?P<year>\d{4})'
result = re.search(date, TEXT)
result.groups()
# ('Jan', '2', '2000')
result.group()
# 'Jan 2nd, 2000'
result.group(0)
# 'Jan 2nd, 2000'
result.group(1)
# 'Jan'
result.group(2)
# '2'
result.group(3)
# '2000'
result.group('year')
# '2000'
result.group('month')
# 'Jan'
result.group('day')
# '2'
result.groupdict()
# {'month': 'Jan', 'day': '2', 'year': '2000'}
import re
TEXT = 'Email from Mark Watney <mwatney@nasa.gov> received on: Sun, Jan 2nd, 2000 at 12:00 AM'
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}nd, {year}'
result = re.search(date, TEXT)
result.groups()
# ('Jan', '2', '2000')
result.group()
# 'Jan 2nd, 2000'
result.group(0)
# 'Jan 2nd, 2000'
result.group(1)
# 'Jan'
result.group(2)
# '2'
result.group(3)
# '2000'
result.group('year')
# '2000'
result.group('month')
# 'Jan'
result.group('day')
# '2'
result.groupdict()
# {'month': 'Jan', 'day': '2', 'year': '2000'}
6.8.9. Case Study 2
import re
TEXT = 'Email from Mark Watney <mwatney@nasa.gov> received on: Sun, Jan 2nd, 2000 at 12:00 AM'
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}nd, {year}'
result = re.search(date, TEXT)
result.group()
# 'Jan 2nd, 2000'
result.groups()
# ('Jan', '2', '2000')
# st - first
# nd - second
# rd - third
# th - forth
import re
TEXT = 'Email from Mark Watney <mwatney@nasa.gov> received on: Sun, Jan 2nd, 2000 at 12:00 AM'
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()
# 'nd'
result.groups()
# (None, None, None)
# st - first
# nd - second
# rd - third
# th - forth
import re
TEXT = 'Email from Mark Watney <mwatney@nasa.gov> received on: Sun, Jan 2nd, 2000 at 12:00 AM'
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 2nd, 2000'
result.groups()
# ('Jan', '2', 'nd', '2000')
# st - first
# nd - second
# rd - third
# th - forth
import re
TEXT = 'Email from Mark Watney <mwatney@nasa.gov> received on: Sun, Jan 2nd, 2000 at 12:00 AM'
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 2nd, 2000'
result.groups()
# ('Jan', '2', '2000')
# st - first
# nd - second
# rd - third
# th - forth
6.8.10. Use Case - 1
Dates
>>> import re
>>> TEXT = 'Email from Mark Watney <mwatney@nasa.gov> received on: Sun, Jan 2nd, 2000 at 12:00 AM'
>>> 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': '2nd', 'year': '2000'}
6.8.11. Use Case - 2
>>> import re
>>> line = 'value=123'
>>>
>>> re.findall(r'(\w+)\s?=\s?(\d+)', line)
[('value', '123')]
>>> line = 'value = 123'
>>>
>>> re.findall(r'(\w+)\s?=\s?(\d+)', line)
[('value', '123')]
6.8.12. Use Case - 3
>>> 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')]
6.8.13. Use Case - 4
>>> import re
>>>
>>>
>>> variable = r'(?P<variable>\w+)'
>>> space = r'\s?(?#optional space)'
>>> value = r'(?P<value>.+)'
>>> assignment = f'^{variable}{space}={space}{value}$'
>>>
>>> assignment
'^(?P<variable>\\w+)\\s?(?#optional space)=\\s?(?#optional space)(?P<value>.+)$'
6.8.14. Assignments
# %% About
# - Name: RE Syntax PositionalGroup
# - Difficulty: medium
# - 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 to find:
# - year
# - month
# - day
# - example: ['July 21, 1969', 'July 21, 1969']
# 2. Define only regex pattern (str), not re.findall(...)
# 3. Use positional groups
# 4. For simplicity, all ordinals (st, th, nd, rd) were removed
# 5. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: str` z wyrażeniem regularnym aby wyszukać:
# - rok
# - miesiąc
# - dzień
# - przykład: ['July 21, 1969', 'July 21, 1969']
# 2. Zdefiniuj tylko wzorzec regex (str), nie re.findall(...)
# 3. Użyj grup pozycyjnych
# 4. Dla uproszczenia, usunięto liczebniki porządkowe (st, th, nd, rd)
# 5. 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(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 -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 PositionalGroup
# - Difficulty: medium
# - 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 to find:
# - year
# - month
# - day
# - example: ['July 21, 1969', 'July 21, 1969']
# 2. Define only regex pattern (str), not re.findall(...)
# 3. Use named groups (year, month, day)
# 4. For simplicity, all ordinals (st, th, nd, rd) were removed
# 5. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: str` z wyrażeniem regularnym,aby wyszukać:
# - rok
# - miesiąc
# - dzień
# - przykład: ['July 21, 1969', 'July 21, 1969']
# 2. Zdefiniuj tylko wzorzec regex (str), nie re.findall(...)
# 3. Użyj grup nazwanych (year, month, day)
# 4. Dla uproszczenia, usunięto liczebniki porządkowe (st, th, nd, rd)
# 5. 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 NonCapturingGroup
# - Difficulty: medium
# - 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 to find:
# - all dates (month name followed by day number), example: ['July 20', 'July 21']
# 2. Define only regex pattern (str), not re.findall(...)
# 3. Use non-capturing group to catch ordinal (st, nd, rd, th)
# 4. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: str` z wyrażeniem regularnym aby wyszukać:
# - wszystkie daty (miesiąc po którym jest dzień), przykład: ['July 20', 'July 21']
# 2. Zdefiniuj tylko wzorzec regex (str), nie re.findall(...)
# 3. Użyj grupy niezłapanej aby złapać liczebnik porządkowy (st, nd, rd, th)
# 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 = re.findall(result, DATA)
>>> pprint(result, compact=True)
['July 20', 'July 21']
"""
# %% 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''
# %% About
# - Name: RE Syntax Group
# - Difficulty: medium
# - Lines: 2
# - 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. Find all duration values
# 2. SKIP durations without hours (only with minutes)
# 3. Define:
# - `result_a`: using positional group, example: [('6', '39'), ('2', '31'), ('21', '36')]
# - `result_b`: using named group, example: [{'hours': '6', 'minutes': '39'}, {'hours': '2', 'minutes': '31'}]
# 4. Define only regex pattern (str), not re.findall(...)
# 5. Run doctests - all must succeed
# %% Polish
# 1. Znajdź wszystkie okresy czasowe
# 2. POMIŃ okresy bez godzin (tylko z minutami)
# 3. Zdefiniuj:
# - `result_a`: używając grupy pozycyjnej, przykład: [('6', '39'), ('2', '31'), ('21', '36')]
# - `result_b`: używając grupy nazwanej, przykład: [{'hours': '6', 'minutes': '39'}, {'hours': '2', 'minutes': '31'}]
# 4. Zdefiniuj tylko wzorzec regex (str), nie re.findall(...)
# 5. 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_a = re.findall(result_a, DATA)
>>> pprint(result_a, compact=True, width=20)
[('6', '39'),
('2', '31'),
('21', '36')]
>>> result_b = re.finditer(result_b, DATA)
>>> result_b = [x.groupdict() for x in result_b]
>>> pprint(result_b, 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_a: str
result_b: 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_a = r''
result_b = r''