7.19. Regex Non-Capturing Group

  • Catch expression results

  • (?:...) - non-capturing group

7.19.1. SetUp

import re

7.19.2. Non-Capturing Group

  • (?:...) - non-capturing group

  • Discard the group from the results

  • Used when you want to use parentheses to group a part of the regular expression

TEXT = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'
re.findall(r'\w{3} \d{1,2}st, \d{4}', TEXT)
['Jan 1st, 2000']

re.findall(r'\w{3} \d{1,2}st|nd|rd|th, \d{4}', TEXT)
['Jan 1st']

re.findall(r'\w{3} \d{1,2}(st|nd|rd|th), \d{4}', TEXT)
['st']

re.findall(r'\w{3} \d{1,2}(?:st|nd|rd|th), \d{4}', TEXT)
['Jan 1st, 2000']

re.findall(r'(\w{3}) (\d{1,2})(?:st|nd|rd|th), (\d{4})', TEXT)
[('Jan', '1', '2000')]

re.findall(r'(\w{3}) (\d{1,2})(st|nd|rd|th), (\d{4})', TEXT)
[('Jan', '1', 'st', '2000')]
date = r'(\w{3} \d{1,2}(?:st|nd|rd|th), \d{4})'
re.findall(date, TEXT)
['Jan 1st, 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)
['st']

re.findall(f'{month} {day}(?:st|nd|rd|th), {year}', TEXT)
['Jan 1st, 2000']

7.19.3. 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 - matches the the or 55 55

  • (.+) \1 - not matches thethe (note the space after the group)

import re
TEXT = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'
re.findall(r'\d{,2}(st|nd|rd|th)?', TEXT)
['', '', '', '', '', '', '', '', '', '', '', '', 'st', '', '', '',
 '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
 '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
 '', '', '', '', '', '', '', '', '', '']

re.findall(r'\d{1,2}(st|nd|rd|th)?', TEXT)
['st', '', '', '', '']

re.findall(r'\d{1,2}(st|nd|rd|th)+?', TEXT)
['st']

re.findall(r'\d{1,2}st|nd|rd|th+?', TEXT)
['1st']

re.findall(r'\d{1,2}(?:st|nd|rd|th)+?', TEXT)
['1st']

re.findall(r'(\d{1,2})(st|nd|rd|th)+?', TEXT)
[('1', 'st')]

re.findall(r'(\d{1,2})(?:st|nd|rd|th)+?', TEXT)
['1']

re.findall(r'(\w{3}) (\d{1,2})(?:st|nd|rd|th)+?, (\d{4})', TEXT)
[('Jan', '1', '2000')]

re.findall(r'(\w{3}) (\d{1,2})(?:st|nd|rd|th)+?, (\d{4})', TEXT)[0]
('Jan', '1', '2000')

re.findall(r'(\w{3} \d{1,2}(?:st|nd|rd|th)+?, \d{4})', TEXT)
['Jan 1st, 2000']

7.19.4. 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.19.5. Assignments

# %% 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 pattern 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 wzorcem wyrażenia regularnego 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 non-capturing aby wył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''