SyntaxStudy
Sign Up
Python Beginner 3 min read

Compiled Patterns

Compiled Patterns

re.compile() compiles a pattern into a reusable regex object. Use it when applying the same pattern many times for better performance.

Example
import re

email_re = re.compile(r"[\w.-]+@[\w.-]+\.\w+")

emails = [
    "user@example.com",
    "invalid-email",
    "other@domain.org",
]
for e in emails:
    if email_re.match(e):
        print(f"Valid: {e}")
Pro Tip

Compiled patterns are reusable across calls and slightly faster.