Python Tutorial · Working with Data · Lesson 35 of 42

Python RegEx

Search, match, extract and replace text with regular expressions (re).

The re module

Example 1Try it yourself
import re

text = "Order 123 shipped on 2026-03-15, order 456 pending"
print(re.search(r"\d+", text).group())
print(re.findall(r"\d+", text))
print(re.findall(r"\d{4}-\d{2}-\d{2}", text))

Output

123
['123', '2026', '03', '15', '456']
['2026-03-15']
Pattern Meaning
\d digit
\w letter, digit or underscore
\s whitespace
. any character
+ / * / ? one or more / zero or more / optional
[abc] any of a, b, c
^ / $ start / end of string
( ) capture group

Always write patterns as raw strings (r"...") so backslashes aren't treated as escapes.

Groups and replacement

Example 2Try it yourself
import re

log = "user=ada action=login ip=10.0.0.5"
match = re.search(r"user=(\w+) action=(\w+)", log)
print(match.group(1), match.group(2))
pairs = dict(re.findall(r"(\w+)=(\S+)", log))
print(pairs)
print(re.sub(r"\d", "*", "card 4111-1111"))

Output

ada login
{'user': 'ada', 'action': 'login', 'ip': '10.0.0.5'}
card ****-****

Validation

re.fullmatch checks that the whole string matches:

Example 3Try it yourself
import re

for code in ["AB-1234", "ab-1234", "AB-12"]:
    print(code, bool(re.fullmatch(r"[A-Z]{2}-\d{4}", code)))

Output

AB-1234 True
ab-1234 False
AB-12 False

Test yourself

Which function returns all matches of a pattern as a list?

  1. re.search()
  2. re.match()
  3. re.findall()
  4. re.sub()
Show answer

Answer: re.findall()

Practice next