若是你们在网上搜索Python 正则表达式
,你将会看到大量的垃圾文章会这样写代码:python
import re
pattern = re.compile('正则表达式')
text = '一段字符串'
result = pattern.findall(text)
复制代码
这些文章的做者,多是被其余语言的坏习惯影响了,也多是被其余垃圾文章误导了,不假思索拿来就用。正则表达式
在Python里面,真的不须要使用re.compile!express
为了证实这一点,咱们来看Python的源代码。缓存
在PyCharm里面输入:微信
import re
re.search
复制代码
而后Windows用户按住键盘上的Ctrl键,鼠标左键点击search
,Mac用户按住键盘上的Command键,鼠标左键点击search
,PyCharm会自动跳转到Python的re模块。在这里,你会看到咱们经常使用的正则表达式方法,不管是findall
仍是search
仍是sub
仍是match
,所有都是这样写的:app
_compile(pattern, flag).对应的方法(string)
复制代码
例如:this
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)
复制代码
以下图所示:spa
而后咱们再来看compile
:3d
def compile(pattern, flags=0):
"Compile a regular expression pattern, returning a Pattern object."
return _compile(pattern, flags)
复制代码
以下图所示:code
看出问题来了吗?
咱们经常使用的正则表达式方法,都已经自带了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)带过来的陋习。
若是这篇文章对你有帮助,请关注个人微信公众号: 未闻Code(ID: itskingname),第一时间获的最新更新: