Python Function Reference

re.compile

Compile a regular expression into a pattern object for reuse.

Python 3.13
re.compile(pattern, flags=0)

Parameters

patternstr | Pattern
The regular expression.
flagsintoptional
Flags such as re.IGNORECASE; combine several flags with |.

Return value

A Pattern object with search, match, findall, sub and other methods.

Examples

Finding numbers with a compiled pattern

Python 3.13
import re
prog = re.compile(r'\d+')
print(prog.findall('12 drummers, 11 pipers'))
['12', '11']

Pattern with a flag

Python 3.13
import re
word = re.compile(r'python', re.IGNORECASE)
print(word.findall('Python, PYTHON, python'))
['Python', 'PYTHON', 'python']

Details

Compiling is useful when one pattern is applied many times. The re module caches recent patterns itself, so it is optional for one-off calls.

See also