python是一个很酷的语言,因为你可以在很短的时间内利用很少的代码做很多事情,再加上正则表达式就更能体现其效果,下面这篇文章主要给大家介绍了关于python中通过预先编译正则表达式提高效率的相关资料,需要的朋友可以参考下。
前言
在re的正则表达式模块里,可以通过模块的方式来访问正则表达式,但是如果重复多次地使用正则表达式,最好是使用compile函数把正则表达式编译成对象regexobject,这样会大大地提高搜索的效率,因为基于非编译方式访问时,是使用模块里的一小块缓冲来进行的。
如下面的例子:
import re
# precompile the patterns
regexes = [
re.compile(p)
for p in ['this', 'that']
]
text = 'http://blog.csdn.net/caimouse is great blog, this is my blog.'
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: 'http://blog.csdn.net/caimouse is great blog, this is my blog.'
seeking "this" -> match!
seeking "that" -> no match
以上就是python编译正则表达式提高效率方法详解的详细内容。