A regular expression is a compact pattern language for describing text shapes — digits, whitespace, repetitions, alternatives — rather than literal substrings. re.match() checks for a match only at the very start of the string, re.search() looks for a match anywhere within it, re.findall() returns every non-overlapping match as a list, and re.sub() replaces matches with a given replacement. Patterns used repeatedly should be compiled once with re.compile(pattern) into a pattern object, which is more efficient than passing the same raw pattern string to a re function on every call.
1Understanding re Module
A regular expression is a compact pattern language for describing text shapes — digits, whitespace, repetitions, alternatives — rather than literal substrings. re.match() checks for a match only at the very start of the string, re.search() looks for a match anywhere within it, re.findall() returns every non-overlapping match as a list, and re.sub() replaces matches with a given replacement. Patterns used repeatedly should be compiled once with re.compile(pattern) into a pattern object, which is more efficient than passing the same raw pattern string to a re function on every call.
Compile a regex once with re.compile() and reuse the resulting pattern object if you're applying the same pattern many times in a loop — recompiling the same pattern string repeatedly wastes work, since Python caches only a small number of recently-used raw patterns internally.
import re
text = "Contact: alice@example.com or bob@example.com"
emails = re.findall(r"[\w.]+@[\w.]+", text)
print(emails)2Practical Example
Here is a real-world application of re Module showing how it is used in production Python code.
import re
text = "Phone: 123-456-7890"
masked = re.sub(r"\d", "*", text)
print(masked)3Best Practices
Follow these guidelines when working with re Module:
1. Compile a pattern with re.compile() when it's used repeatedly, instead of passing the raw string to a re function every time
2. Use raw strings for regex patterns, so backslashes aren't also interpreted as Python string escape sequences
3. Prefer simple string methods like str.split() or the in operator for straightforward text checks — reach for regex only once the matching logic genuinely needs patterns, not just literal text
Tip: Compile a regex once with re.compile() and reuse the resulting pattern object if you're applying the same pattern many times in a loop — recompiling the same pattern string repeatedly wastes work, since Python caches only a small number of recently-used raw patterns internally.
import re
text = "Contact: alice@example.com or bob@example.com"
emails = re.findall(r"[\w.]+@[\w.]+", text)
print(emails)