源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

python中通过预先编译正则表达式提高效率

  • 时间:2022-10-31 04:15 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:python中通过预先编译正则表达式提高效率
[b]前言[/b] 在re的正则表达式模块里,可以通过模块的方式来访问正则表达式,但是如果重复多次地使用正则表达式,最好是使用compile函数把正则表达式编译成对象RegexObject,这样会大大地提高搜索的效率,因为基于非编译方式访问时,是使用模块里的一小块缓冲来进行的。 [b]如下面的例子:[/b]
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
[b]总结[/b] 以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对编程素材网的支持。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部