It is more efficient to compile these expressions for expressions that are frequently used by programs. The compile () function converts an expression string into a regexobject.
The following example is derived from the Python standard library:
Import re
# precompile the patterns
regexes = [Re.compile (p)
for P in [' Here ', ' that ']
]
Text = "Does this text match"
? print ' text:%r\n '% repr (text)
for regex in
regexes: print ' seeking '%s '-> '% Regex.pattern If Regex.search (text):
print ' match! '
else:
print ' no match '
Output:
Text: "' Does this text match the pattern? '"
Seeking "this"-> match!
Seeking "that"-> no match
Module-level functions maintain a cache of compiled expressions. However, the size of this cache is limited, and using compiled expressions directly avoids the cache lookup overhead. Another benefit of using compiled expressions is that by precompiling all expressions while loading a module, you can turn the compilation work to the beginning of the application, rather than to compile when the program responds to a user action.