Skip to content
Justice Tech School

Regular Expressions

The re module searches text with patterns. search finds the first match, findall returns all matches, sub replaces and match checks the beginning. Common pieces: \d digit, \w word character, + one or more, * zero or more, [] a set and () a group. Use raw strings r"..." for patterns.

Example
import re
text = "Call 0801-234-5678 or 0902-111-2222"
print(re.findall(r"\d{4}-\d{3}-\d{4}", text))
m = re.search(r"(\w+)@(\w+)\.com", "mail ada@example.com now")
print(m.group(1), m.group(2))
print(re.sub(r"\s+", " ", "too    many   spaces"))

Result

['0801-234-5678', '0902-111-2222']
ada example
too many spaces

Exercise

Find all matches.

re.(r"\d+", text)

Quiz Test

Why write patterns as raw strings?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.