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.

re functionPython 3 (all)Live demo
Common call
WORD = re.compile(r'\b\w+\b', re.IGNORECASE)
Returns
re.compile('\\b\\w+\\b', re.IGNORECASE) — a re.Pattern
Replaces
repeating the same pattern string (and flags) in many calls
Watch out
Flags go to compile(), not to the Pattern methods
re.compile(patternpattern — The regular expression. A str pattern matches str; a bytes pattern matches bytes.type: str | bytes · required, flagsflags — Combine with |: re.IGNORECASE | re.MULTILINE. Inline flags like (?i) at the start work too.type: re.RegexFlag | int · default: 0=0)
→ re.Pattern

Demo

Live evaluation
The Pattern repr shows the pattern and any flags; .groups counts capturing groups.
Try:
Inputs
patternstra regular expression
Code
import re
pat = re.compile('\\d+')
(pat, pat.groups, pat.groupindex)
Result
(re.compile('\\d+'), 0, {})

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

NameTypeRequiredDescription
patternstr | bytesyesThe regular expression. A str pattern matches str; a bytes pattern matches bytes.
flagsre.RegexFlag | intno (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

Module-level constants
Name the pattern once; compile errors show up at import time.
import re
EMAIL = re.compile(r'[\w.+-]+@[\w-]+(\.[\w-]+)+')
ISO_DATE = re.compile(r'\d{4}-\d{2}-\d{2}')
Flags in the pattern itself
Inline flags travel with the pattern string (config files, databases).
import re
pat = re.compile(r'(?i)^subject:\s*(.*)$', re.MULTILINE)
Clearing the cache
Rarely needed — e.g. in a long-running process that compiled many one-off patterns.
import re
re.purge()

Examples

1. A Pattern object
import re re.compile(r'\d+')
Returns
re.compile('\\d+')
2. Flags in the repr
import re re.compile(r'\d+', re.I | re.M)
Returns
re.compile('\\d+', re.IGNORECASE|re.MULTILINE)
3. Same methods as the module
import re pat = re.compile(r'\d+') (pat.findall('a1b22'), pat.sub('#', 'a1b22'))
Returns
(['1', '22'], 'a#b#')
4. Counting groups
import re re.compile(r'(a)(?P<n>b)(?:c)').groups
Returns
2
5. str patterns get UNICODE
import re re.compile(r'\d+').flags
Returns
32
6. Errors happen at compile time
import re re.compile(r'a{2,1}')
Returns
re.PatternError: min repeat greater than max repeat at position 2
7. purge returns None
import re print(re.purge())
Returns
None

Pitfalls

1. Flags on the method call
Pattern.search's second argument is pos, not flags — re.I (value 2) silently becomes a start position.
pat.search(s, re.I)
import re
pat = re.compile(r'hello')
print(pat.search('Hello hello', re.I))
<re.Match object; span=(6, 11), match='hello'>
compile(..., re.I)
import re
pat = re.compile(r'hello', re.I)
pat.search('Hello hello')
<re.Match object; span=(0, 5), match='Hello'>
2. Compiling inside a hot loop for speed
The module functions already cache compiled patterns, so compile() in the loop body gains nothing. Hoist it out for clarity.
compile per item
import re
[bool(re.compile(r'\d').search(s)) for s in ['a1', 'b']]
[True, False]
compile once
import re
DIGIT = re.compile(r'\d')
[bool(DIGIT.search(s)) for s in ['a1', 'b']]
[True, False]

When to use

Use it
  • 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
Reach for something else
  • A one-off search — re.search(pattern, text) is fine and cached
  • Expecting a big speed-up: the cache already avoids recompiling

Notes

CPython impl
Lib/re/_parser.py builds a parse tree, Lib/re/_compiler.py emits opcodes for the C engine (_sre.compile). re.compile goes through the same cache as the module functions
Cache
Compiled patterns are cached by (type, pattern, flags) — up to 512 of them — so repeated module-level calls do not recompile; re.purge() clears them and the replacement-template cache
Flags
Pattern.flags includes re.UNICODE (32) for every str pattern without re.ASCII, plus inline flags from the pattern
Types
The result is a re.Pattern; a str pattern cannot search bytes and vice versa (TypeError)

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.