更新:
从知乎和stackoverflow的讨论看
https://zhuanlan.zhihu.com/p/70680488
https://stackoverflow.com/questions/452104/is-it-worth-using-pythons-re-compile
实际性能差异根本感知不到,而re.compile可以提高可读性,更通用一些。
-----------------------
转载自:https://blog.youkuaiyun.com/pyjishu/article/details/105413660
如果大家在网上搜索 Python正则表达式,你将会看到大量的垃圾文章会这样写代码:
-
import re -
pattern = re.compile('正则表达式') -
text = '一段字符串' -
result = pattern.findall(text)
这些文章的作者,可能是被其他语言的坏习惯影响了,也可能是被其他垃圾文章误导了,不假思索拿来就用。
在Python里面,真的不需要使用re.compile!
为了证明这一点,我们来看Python的源代码。
在PyCharm里面输入:
-
import re -
re.search
然后Windows用户按住键盘上的Ctrl键,鼠标左键点击 search,Mac用户按住键盘上的Command键,鼠标左键点击 search,PyCharm会自动跳转到Python的re模块。在这里,你会看到我们常用的正则表达式方法,无论是 findall还是 search还是 sub还是 match,全部都是这样写的:
_compile(pattern, flag).对应的方法(string)
例如:
-
def findall(pattern, string, flags=0): -
"""Return a list of all non-overlapping matches in the string. -
If one or more capturing groups are present in the pattern, return -
a list of groups; this will be a list of tuples if the pattern -
has more than one group. -
Empty matches are included in the result.""" -
return _compile(pattern, flags).findall(string)
如下图所示:

然后我们再来看 compile:
-
def compile(pattern, flags=0): -
"Compile a regular expression pattern, returning a Pattern object." -
return _compile(pattern, flags)
如下图所示:

看出问题来了吗?
我们常用的正则表达式方法,都已经自带了 compile了!
根本没有必要多此一举先 re.compile再调用正则表达式方法。
此时,可能会有人反驳:
如果我有一百万条字符串,使用某一个正则表达式去匹配,那么我可以这样写代码:
-
texts = [包含一百万个字符串的列表] -
pattern = re.compile('正则表达式') -
for text in texts: -
pattern.search(text)
这个时候, re.compile只执行了1次,而如果你像下面这样写代码:
-
texts = [包含一百万个字符串的列表] -
for text in texts: -
re.search('正则表达式', text)
相当于你在底层对同一个正则表达式执行了100万次 re.compile。
Talk is cheap, show me the code.
我们来看源代码,正则表达式 re.compile调用的是 _compile,我们就去看 _compile的源代码,如下图所示:

红框中的代码,说明了 _compile自带缓存。它会自动储存最多512条由type(pattern), pattern, flags)组成的Key,只要是同一个正则表达式,同一个flag,那么调用两次_compile时,第二次会直接读取缓存。
综上所述,请你不要再手动调用 re.compile了,这是从其他语言(对的,我说的就是Java)带过来的陋习。
即:-------
List=re.findall(r'正则表达式',txt)
等价于
pattern=re.compile(r'正则表达式')
List=pattern.findall(txt)
-----------------------------------------
Python中使用正则表达式时,实际上并不需要显式调用`re.compile`。大部分正则方法如`findall`, `search`等内部已经包含了编译过程,并且`_compile`函数带有缓存机制,能有效避免重复编译。因此,直接使用正则表达式字符串效率并不低,且代码更简洁。对于大量字符串的匹配,编译模式的优势在于预编译一次,但Python的实现已考虑了性能优化。
2632

被折叠的 条评论
为什么被折叠?



