Python RegEx

Search text with regular expressions.

✍️ 3 exercises + code challenge in this lesson

The re module works with regular expressions: patterns for searching text.

  • re.search(pattern, text): the first match (or None).
  • re.findall(): all matches as a list.
  • re.sub(): replace matches.
  • re.split(): split on a pattern.

Common patterns: \d digit, \w word character, \s whitespace, + one or more, * zero or more, {3} exactly three, [a-z] a range.

Write patterns as raw strings, r"\d+", so backslashes are not treated as escapes.

Key Takeaways: Python RegEx

Mastering Python RegEx helps you write clean and reliable Python code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Python RegEx Code Example

Python
import re

text = "Call 0300-1234567 or 0321-7654321. Email: info@codesintech.com"

print(re.findall(r"\d{4}-\d{7}", text))
email = re.search(r"[\w.]+@[\w.]+", text)
print("Email:", email.group())
print(re.sub(r"\d", "#", "PIN 4821"))
print(re.split(r"[,;]\s*", "a, b;c ,d"))
Free sign-in required · Google login available

Python RegEx Practice Exercises

Check what you learned in “Python RegEx”.

/ 3 solved
Fill in the blank

Find all matches of a pattern.

re.(r"\d+", text)
✓ Correct! Not quite. Try again.
Multiple choice

What does \d match?

✓ Correct! Not quite. Try again.
Code challenge

Use re.findall to print all numbers in the text as a list of strings.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services