What is the output of the following Python program?
import re
s = "Order 42 shipped 7 days ago"
print(re.search(r"\d+", s).group(), re.findall(r"\d+", s))
search returns the first match; findall returns every match as strings.
Regular Expressions · Exercise 2 of 4
Read each Python program and choose what it prints. Every program was run on Python 3, so the answers are the real output.
What is the output of the following Python program?
import re
s = "Order 42 shipped 7 days ago"
print(re.search(r"\d+", s).group(), re.findall(r"\d+", s))
search returns the first match; findall returns every match as strings.
What is the output of the following Python program?
import re
print(re.match(r"\d", "a1"), bool(re.search(r"\d", "a1")), re.match(r"a", "a1").group())
match only checks the beginning, where "a" is not a digit; search finds "1".
What is the output of the following Python program?
import re
for s in ["9845012345", "98450 12345", "98450123456"]:
print(bool(re.fullmatch(r"\d{10}", s)), end=" ")
print(bool(re.search(r"\d{10}", "98450123456")))
fullmatch rejects the space and the eleventh digit; search happily finds 10 digits inside the 11.
What is the output of the following Python program?
import re
m = re.search(r"(\w+)@(\w+)\.com", "mail asha@lf.com now")
print(m.group(0), m.group(1), m.groups(), m.span())
group(0) is the whole match; groups() holds only the captured groups. span() is (start, end) with end exclusive.
What is the output of the following Python program?
import re
m = re.search(r"(?P<day>\d{2})-(?P<mon>\d{2})-(?P<yr>\d{4})", "Born 07-03-2004")
print(m["yr"], m.group("day"), m.groupdict())
Named groups can be read by name; all captured values are strings.
What is the output of the following Python program?
import re
s = "<b>x</b><i>y</i>"
print(re.findall(r"<.*>", s), re.findall(r"<.*?>", s))
Greedy .* runs to the last ">"; lazy .*? stops at the first one each time.
What is the output of the following Python program?
import re
print(repr(re.sub(r"\s+", " ", " a b \t c ")), re.sub(r"a", "X", "banana", count=2))
Each run of whitespace (including the ones at the ends) becomes one space. count=2 replaces only the first two matches.
What is the output of the following Python program?
import re
print(re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\3/\2/\1", "From 2026-11-30 to 2026-12-05"))
sub replaces every match; \3, \2 and \1 insert the captured day, month and year.
What is the output of the following Python program?
import re
print(re.split(r"[,;]\s*", "a, b;c ;d"), re.split(r"(-)", "1-2-3"))
The space before ";" is not part of the separator pattern, so "c " keeps it. A capturing group in split keeps the separators in the result.
What is the output of the following Python program?
import re
pairs = re.findall(r"(\w+)=(\d+)", "x=1 y=22 bad=z")
print(pairs, dict(pairs))
With several groups findall returns tuples; "bad=z" fails because z is not a digit.
Timed online tests with instant scores and explanations.