Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

re.findall

Collects all non-overlapping matches, changing the result shape according to capturing groups.

Version: Python 3.14; repository image, production runtime not attested

Syntax

re.findall(pattern, string, flags=0)

Collects all non-overlapping matches, changing the result shape according to capturing groups.

A single capturing group returns its matched text rather than the full match.

findall scans left to right, collecting nonoverlapping matches, including empty ones. Without captures it returns whole matches. With one capture it returns captured values and with several it returns tuples. In the example parentheses remove id= from each reported value; the second pattern reports the entire fields. After an empty match a nonempty match can start at the same position, so .*? over a produces an empty string, a, then an empty string.

import re
s = "x1 x2"
assert re.findall(r"x\d", s) == ["x1", "x2"]
assert re.findall(r"x(\d)", s) == ["1", "2"]
assert re.findall(r"(x)(\d)", s) == [("x", "1"), ("x", "2")]
assert re.findall(r"z*", "") == [""]
assert re.findall(".*?", "a") == ["", "a", ""]

Examples

import re
print(re.findall(r"id=(\d+)", "id=3 id=17"))
print(re.findall(r"id=\d+", "id=3 id=17"))

Result

['3', '17']
['id=3', 'id=17']

findall scans left to right, collecting nonoverlapping matches, including empty ones. Without captures it returns whole matches. With one capture it returns captured values and with several it returns tuples. In the example parentheses remove id= from each reported value; the second pattern reports the entire fields. After an empty match a nonempty match can start at the same position, so .*? over a produces an empty string, a, then an empty string.

Sources