Intermediate LevelPython
How do you optimize regular expression matching using re.compile() and raw strings (r"\d+") in the re module?
❓ Interview Prompt: Explain `re` module, raw strings (`r'pattern'`), `re.compile()`, match objects (`match`, `search`, `findall`), and pre-compiling regexes.
1. Raw Strings ('r'pattern''):
Always prefix regex patterns with 'r' to treat backslashes as literal characters rather than Python string escape sequences.
2. Pre-Compiling ('re.compile()'):
Pre-compiling regex patterns into regex objects once at module import avoids re-parsing pattern syntax on every function call!
Code Implementation Example
python
import re
# Pre-compile regex pattern at module load time
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$')
def is_valid_email(email):
return bool(EMAIL_REGEX.match(email))
print(is_valid_email('alice@example.com')) # True💡Pre-compiling regular expressions for high-performance string matching.
🎯 Interview Key Takeaway
Pre-compile regex patterns with re.compile() at module load time to avoid repetitive parsing overhead.
#re module#Regex#re.compile#Intermediate
Back to all Python Questions→