CodeMIRAI
0 XP

Regular expressions

2 min read 5 runnable examples Quiz included

A regular expression (regex) is a pattern that describes text: "a word of digits", "something that looks like an email". Python's re module searches text for such patterns.

search and findall

Python
import re

text = "Order 4521 shipped on 2026-10-29 to Mumbai."

match = re.search(r"\d+", text)          # the first run of digits
print(match.group())

print(re.findall(r"\d+", text))           # every run of digits

Always write patterns as raw strings (r"...") so backslashes reach re unchanged.

The essential symbols

PatternMatches
\da digit
\wa word character: letter, digit or _
\swhitespace
.any character except a newline
[abc] / [a-z]one of these characters / a range
+one or more of the previous item
*zero or more
?zero or one (optional)
{3} / {2,4}exactly 3 / between 2 and 4
^ / $start / end of the text
\ba word boundary
Python
import re

print(re.findall(r"\b\w{5}\b", "Learn regex with Python today"))  # 5-letter words
print(re.findall(r"[A-Z]\w+", "Asha met Leo and Mei in Osaka"))    # capitalised words
print(bool(re.fullmatch(r"\d{6}", "400001")))                       # a 6-digit PIN code

Groups: extracting parts

Brackets create groups, so you can pull out the pieces of a match:

Python
import re

match = re.search(r"(\d{4})-(\d{2})-(\d{2})", "Shipped on 2026-10-29.")
year, month, day = match.groups()
print(year, month, day)

for name, score in re.findall(r"(\w+): (\d+)", "Asha: 92, Leo: 78, Mei: 85"):
    print(name, int(score))

Validating input

Python
import re

EMAIL = re.compile(r"^[\w.+-]+@[\w-]+\.[\w.-]+$")
for address in ["asha@example.com", "leo.kim+news@mail.co.uk", "not-an-email", "a@b"]:
    print(f"{address:28} {'valid' if EMAIL.match(address) else 'invalid'}")

re.compile builds a reusable pattern object, which is faster when you use it many times. (Real email validation is notoriously hard; this simple pattern catches obvious mistakes.)

Replacing with sub

Python
import re

phone = "Call +91 98765-43210 now"
print(re.sub(r"\d", "#", phone))                       # hide every digit
print(re.sub(r"\s+", " ", "too    many     spaces"))   # collapse whitespace
print(re.sub(r"(\w+)@(\w+)", r"\2 at \1", "user@example"))   # reuse groups with \1, \2
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.