1.3.2 编译表达式
尽管re包括模块级函数,可以处理作为文本字符串的正则表达式,但是对于程序频繁使用的表达式而言,编译它们会更为高效。compile()函数会把一个表达式字符串转换为一个Regexobject.
import re
# Precompile the patterns.
regexes = [
re.compile(p)
for p in ['this','that']
]
text = 'Does this text match the pattern?'
print('Text: {!r}\n'.format(text))
for regex in regexes:
print('Seeking "{}" ->'.format(regex.pattern),end=' ')
if regex.search(text):
print('match!')
else:
print('no match!')
模块级函数会维护一个包含已编译表达式的缓存,不过这个缓存的大小是有限的,另外直接使用已编译表达式可以避免与缓存查找相关的开销。使用已编译表达式的另一个好处是,通过在加载模块时预编译所有表达式,可以把编译工作转移到应用开始时,而不是当程序响应一个用户动作时才编译。
运行结果:
Text: ‘Does this text match the pattern?’
Seeking “this” -> match!
Seeking “that” -> no match!