Codzy

Regular expressions

A regular expression (regex) is a pattern describing text to look for: \d means "a digit", \w "a letter, digit or underscore", and + "one or more times". Patterns are written in raw strings, like r"\d+".

The re module provides re.findall() to find all matches, re.search() to find the first one and re.sub() to replace. It's very handy for pulling numbers, emails or dates out of a text.

import re

text = "Call 06 12 34 56 78 or write to [email protected]"
print(re.findall(r"\d+", text))
print(re.search(r"\w+@\w+\.\w+", text).group())
print(re.sub(r"\d", "#", "Code 2026"))

Start the lesson