PyForge ยท Python practice library
All topics

Topic 17 of 17

Regular Expressions

Pattern-match text with Python's re module.

search/match/findall
Groups
Substitution
Flags

Basic

1 program

Program 1

Find all numbers

Basic

Extract digits from a string.

python
import re

text = "Order 42 ships on day 7 with code 100x"
nums = re.findall(r"\d+", text)
print(nums)

Intermediate

2 programs

Program 1

Validate email

Intermediate

A simple email pattern check.

python
import re

pattern = r"^[w.-]+@[w-]+.[a-zA-Z]{2,}$"
for e in ["a@b.com", "bad@", "ok.user@mail.co"]:
    print(e, bool(re.match(pattern, e)))

Program 2

Replace whitespace

Intermediate

Collapse multiple spaces into one.

python
import re

s = "this    has   too	many   spaces"
clean = re.sub(r"s+", " ", s)
print(clean)

Advanced

1 program

Program 1

Named groups

Advanced

Parse a date with named groups.

python
import re

m = re.match(r"(?P<y>d{4})-(?P<m>d{2})-(?P<d>d{2})", "2026-06-05")
if m:
    print(m.group("y"), m.group("m"), m.group("d"))