Python Glossary Русский

all Python 3refunction

re.compile()

compilation

Compiles a pattern into an re.Pattern object that can be reused. It speeds up repeated operations.

Syntax

re.compile(pattern, flags=0)

The speedup is usually smaller than you expect: the module-level re.findall/re.search already cache compiled patterns, so compile mostly buys readability by keeping the pattern in one place. The object's own API is the real gain — its methods take pos and endpos to restrict the search to part of the string without copying it, and flags are fixed once at compile time.

Examples

import re
pat = re.compile(r'\d+')
pat.findall('a1 b22') # → ['1', '22']
pat.sub('X', 'a1b2') # → 'aXbX'
pat.match('123abc').group() # → '123'
pat2 = re.compile(r'hello', re.IGNORECASE)
bool(pat2.search('Hello World')) # → True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy