All lessons
πŸ”Ž

Regular Expressions

Pattern matching with re

Reward
+50 XP

Basic regex

The re module lets you search for patterns in strings.

import re
result = re.search(r"\d+", "I have 42 apples")
if result:
    print(result.group())  # 42

Common patterns

\d (digit), \w (word char), \s (whitespace), . (any char), * (0+), + (1+), ? (0 or 1).

import re
matches = re.findall(r"\b\w+@\w+\.\w+\b", "Email me at a@b.com")
print(matches)

Try it yourself

Run the example below. Edit it and see what changes.

main.py
Output
Press Run to execute (Ctrl/Cmd+Enter)

Common mistakes

  • ⚠Forgetting the r prefix for raw strings (needed for backslashes).
  • ⚠Using match() when you want search() β€” match only checks the start.