re.compile
Turn a pattern string into a Pattern object once, then call its methods. Errors in the pattern surface here, at compile time. re.purge() empties the internal cache of patterns compiled by the module-level functions.
Demo
import re pat = re.compile('\\d+') (pat, pat.groups, pat.groupindex)
The repr repeats your pattern (backslashes doubled, as repr does) and lists flags; inline flags stay inside the pattern text. groupindex maps names to group numbers — it is an empty {} when there are no named groups. 'errors=0' is not a match for \b(error|fatal)\b because there is no word boundary between error and s.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| pattern | str | bytes | yes | The regular expression. A str pattern matches str; a bytes pattern matches bytes. |
| flags | re.RegexFlag | int | no (0) | Combine with |: re.IGNORECASE | re.MULTILINE. Inline flags like (?i) at the start work too. |
Return value
re.Pattern — A compiled pattern with search, match, fullmatch, findall, finditer, sub, subn and split methods.
Common patterns
import re EMAIL = re.compile(r'[\w.+-]+@[\w-]+(\.[\w-]+)+') ISO_DATE = re.compile(r'\d{4}-\d{2}-\d{2}')
import re pat = re.compile(r'(?i)^subject:\s*(.*)$', re.MULTILINE)
import re re.purge()
Examples
Pitfalls
import re pat = re.compile(r'hello') print(pat.search('Hello hello', re.I))
import re pat = re.compile(r'hello', re.I) pat.search('Hello hello')
import re [bool(re.compile(r'\d').search(s)) for s in ['a1', 'b']]
import re DIGIT = re.compile(r'\d') [bool(DIGIT.search(s)) for s in ['a1', 'b']]
When to use
- A pattern used in several places or many times — give it a name
- Validating patterns early (at import) instead of at first use
- Pattern methods with pos/endpos, which the module functions lack
- A one-off search — re.search(pattern, text) is fine and cached
- Expecting a big speed-up: the cache already avoids recompiling
Notes
FAQ
Only marginally: re.search and friends compile the pattern and keep it in a cache (512 entries), so repeated calls do not recompile. re.compile skips the cache lookup and makes the code clearer.