Regular expressions · 3 / 15 Theory

findall, finditer and groups

When you want all the matches, not just the first one, there are two functions: findall and finditer.

findall: a list with everything

import re

text = "I have 3 cats and 12 fish"

print(re.findall(r"\d+", text))  # ['3', '12']

numbers = [int(n) for n in re.findall(r"\d+", text)]
print(sum(numbers))  # 15

findall returns a list of strings. If there are no matches, it returns an empty list.

finditer: Match objects with positions

import re

for m in re.finditer(r"\d+", "a1 b22 c333"):
    print(m.group(), m.start())
# 1 1
# 22 4
# 333 8

Groups with parentheses

Parentheses group a part of the pattern and let you extract it separately:

import re

r = re.fullmatch(r"(\d{2})/(\d{2})/(\d{4})", "13/11/2026")

print(r.group())    # 13/11/2026
print(r.group(1))   # 13
print(r.group(2))   # 11
print(r.groups())   # ('13', '11', '2026')

day, month, year = r.groups()
print(year)         # 2026

group(0) or group() is the whole text; group(1), group(2)… are the groups, numbered by the order of their opening parenthesis.

Named groups

If the pattern is long, it is clearer to name the groups with (?P<name>...):

import re

r = re.fullmatch(r"(?P<day>\d{2})/(?P<month>\d{2})/(?P<year>\d{4})", "13/11/2026")

print(r.group("month"))   # 11
print(r.groupdict())     # {'day': '13', 'month': '11', 'year': '2026'}

findall with groups

Careful: if the pattern has groups, findall returns only what each group captures:

import re

text = "a=1, b=2"

print(re.findall(r"\w=\d", text))        # ['a=1', 'b=2']
print(re.findall(r"(\w)=(\d)", text))    # [('a', '1'), ('b', '2')]

Alternatives with |

The vertical bar means "or". Parentheses delimit where the alternative starts and ends:

import re

print(bool(re.fullmatch(r"(cat|dog)s?", "dogs")))     # True
print(bool(re.fullmatch(r"(cat|dog)s?", "bird")))     # False

Practice with All the numbers, Hashtags and mentions and Date with groups.