Python Regex in Practice
A compiled pattern is a pattern built once for reuse. re.compile() builds that pattern object.
Compile once, reuse often
A compiled pattern is a ready-to-use pattern object.
import re
pattern = re.compile(r"\d+")
print(pattern.findall("Room 12 has 40 chairs"))Check for no match
search returns None when nothing matches. Test for None instead of printing the Match.
import re
pattern = re.compile(r"\d+")
match = pattern.search("no digits here")
print(match is None)Verbose patterns
Verbose mode ignores spaces in the pattern. Comments make long patterns readable.
import re
pattern = re.compile(r"""
\d{4} # year
- # dash
\d{2} # month
""", re.VERBOSE)
print(pattern.search("date 2026-10-22 end").group())A validation trio
fullmatch checks that the whole string fits. These three checks cover common shapes.
import re
print(bool(re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", "ana@test.org")))
print(bool(re.fullmatch(r"\d{4}-\d{2}-\d{2}", "2026-10-22")))
print(bool(re.fullmatch(r"[A-Z]{2}\d{2}", "AB12")))When regex is the wrong tool
HTML has nested tags. Nested data needs a real parser. For simple flat text, plain string methods can be clearer.
# For HTML, use html.parser from the standard library.
# For JSON, use the json module.
# Use regex for flat text with a clear pattern.Example
import re
lines = [
"2026-10-22 INFO Server started",
"2026-10-22 ERROR Disk full",
"2026-10-23 INFO Backup done",
]
pattern = re.compile(r"(?P<date>\d{4}-\d{2}-\d{2}) (?P<level>INFO|ERROR) (?P<msg>.*)")
for line in lines:
match = pattern.match(line)
print(match.group("date"), "|", match.group("level"), "|", match.group("msg"))Key points
- Use re.compile() to build a pattern once and reuse it
- Use verbose mode with (?x) or re.VERBOSE to spread a pattern over lines
- Use fullmatch() when the whole string must fit the pattern
- Use a real parser for HTML or nested data instead of regex
In this example, each log line has the same shape. The pattern is compiled once before the loop. Named groups capture the date, the level, and the message. The loop matches each line and prints the three parts. The same compiled pattern works for every line.
Note
Regex checks shape, not meaning.
It can check that a date looks right, but not that the day exists.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Why compile a pattern with re.compile()?