我试图比较re.match和re.search使用timeit模块,我发现当我想要找到的字符串位于字符串的开头时,匹配比搜索更好.
>>> s1 = '''
... import re
... re.search(r'hello','helloab'*100000)
... '''
>>> timeit.timeit(stmt=s1,number=10000)
32.12064480781555
>>> s = '''
... import re
... re.match(r'hello','helloab'*100000)
... '''
>>> timeit.timeit(stmt=s,number=10000)
30.9136700630188
Run Code Online (Sandbox Code Playgroud)
现在,我知道匹配在字符串的开头查找模式并返回一个对象(如果找到),但我想知道搜索是如何操作的.
在开头找到字符串后,搜索是否会执行任何额外的匹配,从而减慢它的速度?
更新
在使用@David Robinsons代码后,我得到了他的结果.
>>> print timeit.timeit(stmt="r.match('hello')",
... setup="import re; s = 'helloab'*100000; r = re.compile('hello')",
... number = 10000000)
49.9567620754
>>> print timeit.timeit(stmt="r.search('hello')",
... setup="import re; s = 'helloab'*100000; r = re.compile('hello')",
... number = 10000000)
35.6694438457
Run Code Online (Sandbox Code Playgroud)
那么,更新后的问题现在为什么search表现不佳match?