7.14. Regex Quantifier Greedy

  • Quantifier specifies how many occurrences of preceding qualifier or character class

  • Greedy

7.14.1. SetUp

import re

7.14.2. Greedy

  • Prefer longest matches

  • Works better with numbers

  • Not that good results for text

  • Default behavior

  • {n,m} - minimum n repetitions, maximum m times, prefer longer

  • {,n} - maximum n repetitions, prefer longer

  • {n,} - minimum n repetitions, prefer longer

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

Min/max:

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

Nolimit:

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

Note

Note, that zero (none) digits is a valid match for \d{,4}.

7.14.3. Shorthand

  • * - minimum 0 repetitions, no maximum, prefer longer (alias to {0,})

  • + - minimum 1 repetitions, no maximum, prefer longer (alias to {1,})

  • ? - minimum 0 repetitions, maximum 1 repetitions, prefer longer (alias to {0,1})

Plus:

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

Star:

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

Question mark:

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

Note

Both star and question mark does not make any sense with numbers. They works better with text.

7.14.4. Case Study 1

import re

html = '<p>Hello World</p>'

re.findall(r'<p>', html)
# ['<p>']

re.findall(r'</p>', html)
# ['</p>']

re.findall(r'</{0,1}p>', html)
# ['<p>', '</p>']

re.findall(r'</?p>', html)
# ['<p>', '</p>']

7.14.5. Case Study 2

import re

CODE = """

name = "Mark"
print(name)

"""

# %%

variable = re.findall(r'^(\w{1,}) =', CODE, flags=re.MULTILINE)
print(variable)

# %%

variable = re.findall(r'^(\w+) =', CODE, flags=re.MULTILINE)
print(variable)

import re

CODE = """

name ="Mark"
print(name)

"""

# %%

variable = re.findall(r'^(\w{1,})\s{0,1}=\s{0,1}', CODE, flags=re.MULTILINE)
print(variable)

# %%

variable = re.findall(r'^(\w+)\s?=\s?', CODE, flags=re.MULTILINE)
print(variable)

import re

CODE = """

name ="Mark"
print(name)

"""

# %%

variable = re.findall(r'^(\w{1,})\s{0,1}=\s{0,1}".{0,}"', CODE, flags=re.MULTILINE)
print(variable)

# %%

variable = re.findall(r'^(\w+)\s?=\s?".*"', CODE, flags=re.MULTILINE)
print(variable)


# name = ""
# name = "a"
# name = "abc"
import re

CODE = """

name =      "Mark"
print(name)

"""

# %%

variable = re.findall(r'^(\w{1,})\s{0,}=\s{0,}".{0,}"', CODE, flags=re.MULTILINE)
print(variable)

# %%

variable = re.findall(r'^(\w+)\s*=\s*".*"', CODE, flags=re.MULTILINE)
print(variable)


# name = ""
# name = "a"
# name = "abc"

7.14.6. Case Study 3

import re

html = '<p>Hello World</p>'


# %%

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

# %%

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

7.14.7. Case Study 4

import re
from pprint import pprint

text = 'Litwo. Ojczyzno moja. Ty jesteś jak zdrowie. Ile cię trzeba cenić, ten tylko się dowie, kto cię stracił. [bla, bla, bla] I ja tam z gośćmi byłem, miód i wino piłem. A com wiedział i słyszał, w księgi umieściłem.'


# %% Greedy

zdania = re.findall(r'[A-Z].+\.', text)  # do najdalszej kropki

len(zdania)
# 1

print(zdania)
# ['Litwo. Ojczyzno moja. Ty jesteś jak zdrowie. Ile cię trzeba cenić, ten tylko się dowie, kto cię stracił. [bla, bla, bla] I ja tam z gośćmi byłem, miód i wino piłem. A com wiedział i słyszał, w księgi umieściłem.']


# %% Lazy

zdania = re.findall(r'[A-Z].+?\.', text)  # do najbliższej kropki

len(zdania)
# 6

pprint(zdania)
# ['Litwo.',
#  'Ojczyzno moja.',
#  'Ty jesteś jak zdrowie.',
#  'Ile cię trzeba cenić, ten tylko się dowie, kto cię stracił.',
#  'I ja tam z gośćmi byłem, miód i wino piłem.',
#  'A com wiedział i słyszał, w księgi umieściłem.']

7.14.8. Examples

  • [0-9]{2} - exactly two digits from 0 to 9

  • \d{2} - exactly two digits from 0 to 9

  • [A-Z]{2,10} - two to ten uppercase letters from A to Z

  • [A-Z]{2-10}-[0-9]{,5} - two to ten uppercase letters from A to Z followed by dash (-) and at least five numbers

  • [a-z]+ - at least one lowercase letter from a to z, but try to fit the longest match

  • \d+ - number

  • \d+\.\d+ - float

7.14.9. Use Case - 1

  • Float

TEXT = 'Pi number is 3.1415...'
pi = re.findall(r'\d+\.\d+', TEXT)

pi
['3.1415']

7.14.10. Use Case - 2

TEXT = 'On Sun, Jan 1st, 2000 at 12:00 AM Alice <alice@example.com> wrote'
result = re.findall(r'\d\d:\d\d', TEXT)

result
['12:00']

7.14.11. Use Case - 3

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

result
['Jan 1st, 2000']

7.14.12. Use Case - 4

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')]

7.14.13. Use Case - 6

HTML = '<h1>Header 1</h1><p>Paragraph 1</p><p>Paragraph 2</p>'
re.findall(r'<p>', HTML)
['<p>', '<p>']
re.findall(r'</p>', HTML)
['</p>', '</p>']
re.findall(r'</?p>', HTML)
['<p>', '</p>', '<p>', '</p>']

7.14.14. Assignments

# %% About
# - Name: RE Syntax Quantifier
# - Difficulty: easy
# - Lines: 2
# - 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_a: str` with regular expression pattern to find
#    all integers (as long as possible)
#    example: ['11', '20', '1969', ...]
# 2. Define `result_b: str` with regular expression pattern to find
#    all floats
#    example: ['47.5', '21.5']
# 3. Define only regex pattern (str), not re.findall(...)
# 4. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result_a: str` z wzorcem wyrażenia regularnego aby wyszukać
#    wszystkie liczby całkowite (jak najdłuższe)
#    przykład: ['11', '20', '1969', ...]
# 2. Zdefiniuj `result_b: str` z wzorcem wyrażenia regularnego aby wyszukać
#    wszystkie liczby z ułamkami dziesiętnymi
#    przykład: ['47.5', '21.5']
# 3. Zdefiniuj tylko wzorzec regex (str), nie re.findall(...)
# 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_a, DATA)
>>> pprint(result, compact=True, width=72)
['11', '20', '1969', '20', '17', '6', '39', '21', '1969', '02', '56',
 '15', '19', '2', '31', '47', '5', '21', '5', '21', '36']

>>> result = re.findall(result_b, DATA)
>>> pprint(result, compact=True, width=72)
['47.5', '21.5']
"""

# %% 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''

# %% About
# - Name: RE Syntax Quantifier
# - Difficulty: easy
# - Lines: 3
# - 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_a: str` with regular expression pattern to find
#    all capitalized words
#    example: ['Apollo', 'Moon', 'Commander', 'Neil', 'Armstrong', ...]
# 2. Define `result_b: str` with regular expression pattern to find
#    all names (two capitalized words)
#    example: ['Neil Armstrong', 'Buzz Aldrin', 'Apollo Lunar', 'Tranquility Base', ...]
# 3. Define `result_c: str` with regular expression pattern to find
#    all names with numbers (capitalized word, space and number)
#    example: ['Apollo 11']
# 4. Define only regex pattern (str), not re.findall(...)
# 5. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result_a: str` z wzorcem wyrażenia regularnego aby wyszukać
#    słowa zaczynające się wielką literą
#    przykład: ['Apollo', 'Moon', 'Commander', 'Neil', 'Armstrong', ...]
# 2. Zdefiniuj `result_b: str` z wzorcem wyrażenia regularnego aby wyszukać
#    wszystkie nazwy (dwa słowa zaczynające się wielką literą)
#    przykład: ['Neil Armstrong', 'Buzz Aldrin', 'Apollo Lunar', 'Tranquility Base', ...]
# 3. Zdefiniuj `result_c: str` z wzorcem wyrażenia regularnego aby wyszukać
#    wszystkie nazwy z numerami (słowo z dużej litery, spacja i liczba)
#    przykład: ['Apollo 11']
# 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 = re.findall(result_a, DATA)
>>> pprint(result, compact=True, width=72)
['Apollo', 'American', 'Moon', 'Commander', 'Neil', 'Armstrong', 'Buzz',
 'Aldrin', 'Apollo', 'Lunar', 'Module', 'Eagle', 'July', 'Armstrong',
 'Moon', 'July', 'Aldrin', 'They', 'Tranquility', 'Base', 'Armstrong',
 'Aldrin', 'Earth', 'Michael', 'Collins', 'Command', 'Module',
 'Columbia', 'Moon', 'Columbia']

>>> result = re.findall(result_b, DATA)
>>> pprint(result, compact=True, width=72)
['Neil Armstrong', 'Buzz Aldrin', 'Apollo Lunar', 'Tranquility Base',
 'Michael Collins', 'Command Module']

>>> result = re.findall(result_c, DATA)
>>> pprint(result, compact=True, width=72)
['Apollo 11']
"""

# %% 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
result_c: 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''
result_c = r''

# %% About
# - Name: RE Syntax Quantifier
# - Difficulty: easy
# - Lines: 3
# - 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_a: str` with regular expression pattern to find
#    times (hours and minutes)
#    example: ['20:17', '02:56']
# 2. Define `result_b: str` with regular expression pattern to find
#    dates in US long format
#    example: ['July 20, 1969', 'July 21, 1969']
# 3. Define `result_c: str` with regular expression pattern to find
#    durations in text
#    example: ['6 hours 39 minutes', '2 hours 31 minutes', '21 hours 36 minutes']
# 4. Define only regex pattern (str), not re.findall(...)
# 5. Run doctests - all must succeed

# %% Polish
# 1. Zdefiniuj `result_a: str` z wzorcem wyrażenia regularnego aby wyszukać
#    czasy (godziny z minutami)
#    przykład: ['20:17', '02:56']
# 2. Zdefiniuj `result_b: str` z wzorcem wyrażenia regularnego aby wyszukać
#    daty w formacie amerykańskim długim
#    przykład: ['July 20, 1969', 'July 21, 1969']
# 3. Zdefiniuj `result_c: str` z wzorcem wyrażenia regularnego aby wyszukać
#    okresy
#    przykład: ['6 hours 39 minutes', '2 hours 31 minutes', '21 hours 36 minutes']
# 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 = re.findall(result_a, DATA)
>>> pprint(result, compact=True, width=72)
['20:17', '02:56']

>>> result = re.findall(result_b, DATA)
>>> pprint(result, compact=True, width=72)
['July 20, 1969', 'July 21, 1969']

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

# %% 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
result_c: 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_a = r''
result_b = r''
result_c = r''