Python regex `compile` function

Python regex compile() function explained with examples. Includes learning tasks.

Python regex compile

The compile function compiles a regular expression pattern into a regular expression object, which can be used for matching using its match(), search(), etc. methods.

Syntax

 re.compile(pattern, flags=0)

The expression’s behaviour can be modified by specifying a flags value (discussed earlier). Values can be any of the following variables, combined using bitwise OR (the | operator).

For example:

m = re.match(pattern, string)

is equivalent to:

p = re.compile(pattern)
m = p.match(string)

Note that the programs that use only a few regular expressions at a time don’t need to compile regular expressions (recent patterns are cached automatically due to re._MAXCACHE setting).

Get hands-on with 1200+ tech skills courses.