什么';Python正则表达式中允许的最大重复次数是多少?
在Python 2.7和3中,以下工作:什么';Python正则表达式中允许的最大重复次数是多少?,python,regex,Python,Regex,在Python 2.7和3中,以下工作: >>> re.search(r"a{1,9999}", 'aaa') <_sre.SRE_Match object at 0x1f5d100> 重新搜索(r“a{19999},'aaa') 但这会产生一个错误: >>> re.search(r"a{1,99999}", 'aaa') Traceback (most recent call last): File "<stdin>",
>>> re.search(r"a{1,9999}", 'aaa')
<_sre.SRE_Match object at 0x1f5d100>
重新搜索(r“a{19999},'aaa')
但这会产生一个错误:
>>> re.search(r"a{1,99999}", 'aaa')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/re.py", line 142, in search
return _compile(pattern, flags).search(string)
File "/usr/lib/python2.7/re.py", line 240, in _compile
p = sre_compile.compile(pattern, flags)
File "/usr/lib/python2.7/sre_compile.py", line 523, in compile
groupindex, indexgroup
RuntimeError: invalid SRE code
>>重新搜索(r“a{199999},'aaa')
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“/usr/lib/python2.7/re.py”,第142行,搜索中
返回编译(模式、标志)。搜索(字符串)
文件“/usr/lib/python2.7/re.py”,第240行,在编译中
p=sre_compile.compile(模式、标志)
文件“/usr/lib/python2.7/sre_compile.py”,第523行,在compile中
组索引,索引组
运行时错误:SRE代码无效
似乎重复次数是有上限的。这是正则表达式规范的一部分,还是特定于Python的限制?如果是特定于Python的,那么实际的数字是否记录在某个地方,在不同的实现中是否有所不同?一个快速的手动二进制搜索给出了答案,特别是65535:
>>> re.search(r"a{1,65535}", 'aaa')
<_sre.SRE_Match object at 0x2a9a68>
>>>
>>> re.search(r"a{1,65536}", 'aaa')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/re.py", line 142, in search
return _compile(pattern, flags).search(string)
File "/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/re.py", line 240, in _compile
p = sre_compile.compile(pattern, flags)
File "/Library/Frameworks/Python.framework/Versions/7.3/lib/python2.7/sre_compile.py", line 523, in compile
groupindex, indexgroup
OverflowError: regular expression code size limit exceeded
(@MarkkuK.和@hcwhsa)
如果您想在回答中指出这一点:对于CPython,此限制也在中实现,如果您查看sre_constants.py,您将发现
maxreat=65535
可以使用以下方法找到限制:import sre_constants;打印sre_常量。maxreat
谢谢,我已将此添加到答案中。请注意,sre_常量。maxreat
不一定是非CPython实现中的限制。在Pypy2.0.0-beta1、Jython2.5.1+
和IronPython2.9.9a0
上成功地测试了len(重新搜索(r“a{1999999}”、“a”*(2*10**6)).group()。尽管pypy
和jython
都有sre_常量,但这一点仍然有效。maxreat==65535
。
>>> import sre_constants
>>>
>>> sre_constants.MAXREPEAT
65535