Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

re.compile

Compiles a regular expression into a reusable pattern object.

Version: Python 3.14; repository image, production runtime not attested

Syntax

re.compile(pattern, flags=0)

Compiles a regular expression into a reusable pattern object.

Flags attach to the compiled pattern and affect each later match, including matches with different letter case.

The reusable Pattern retains its source and flags; reuse its methods for multiple strings of the same kind (str or bytes). Here re.I makes case irrelevant and b+ requires at least one b, so AbB is returned with its original case. Abx fails a full match. Invalid pattern syntax raises re.PatternError during compilation. Module-level regex functions and compile reuse a cache of recently compiled patterns.

import re
p = re.compile("ab+", re.I)
assert p.fullmatch("AbB").group() == "AbB" and p.fullmatch("Abx") is None
try:
    re.compile("(")
except re.PatternError as e:
    assert e.pos == 0
else:
    raise AssertionError
assert re.compile('a').pattern == 'a'

Examples

import re
pattern = re.compile(r"ab+", re.I)
print(pattern.fullmatch("AbB").group())
print(pattern.fullmatch("Abx"))

Result

AbB
None

The reusable Pattern retains its source and flags; reuse its methods for multiple strings of the same kind (str or bytes). Here re.I makes case irrelevant and b+ requires at least one b, so AbB is returned with its original case. Abx fails a full match. Invalid pattern syntax raises re.PatternError during compilation. Module-level regex functions and compile reuse a cache of recently compiled patterns.

Sources