Compiled Patterns
re.compile() compiles a pattern into a reusable regex object. Use it when applying the same pattern many times for better performance.
re.compile() compiles a pattern into a reusable regex object. Use it when applying the same pattern many times for better performance.
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}")
Compiled patterns are reusable across calls and slightly faster.