Python正则之预编译表达式re.compile()

来源:互联网 发布:淘宝直通车行业点击率 编辑:程序博客网 时间:2024/06/05 18:59

对于程序频繁使用的表达式,编译这些表达式会更有效。compile()函数会把一个表达式字符串转化成为一个RegexObject。

下面这个例子出自《Python标准库》:


import re# Precompile the patternsregexes = [re.compile(p)            for p in ['this', 'that']           ]text = "Does this text match the pattern?"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'

输出:

Text: "'Does this text match the pattern?'"


Seeking "this"-> match!
Seeking "that"-> no match


模块级函数会维护已编译表达式的一个缓存。不过,这个缓存的大小是有限的,直接使用已编译的表达式可以避免缓存查找开销。使用已编译表达式的另一个好处是,通过在加载模块时预编译所有表达式,可以把编译工作转到应用开始时,而不是当程序响应一个用户动作时才进行编译。



1 0
原创粉丝点击