确定正则表达式的最大匹配长度的最简单方法是什么?
具体来说,我正在使用Python的re
模块.
例如foo((bar){2,3}|potato)
它将是12.
显然,正则表达式使用运算符等*
和+
具有理论上无限匹配长度; 在那些情况下返回错误或某事是好的.使用(?...)
扩展程序为正则表达式提供错误也很好.
我也可以获得一个近似的上限,只要它总是大于实际的最大长度,但不要太大.
import invRegex
data='foo(bar{2,3}|potato)'
print(list(invRegex.invert(data)))
# ['foobarr', 'foobarrr', 'foopotato']
print(max(map(len,invRegex.invert(data))))
# 9
Run Code Online (Sandbox Code Playgroud)
另一种替代方法是使用ipermute
从该模块.
import inverse_regex
data='foo(bar{2,3}|potato)'
print(list(inverse_regex.ipermute(data)))
# ['foobarr', 'foobarrr', 'foopotato']
print(max(map(len,inverse_regex.ipermute(data))))
# 9
Run Code Online (Sandbox Code Playgroud)
解决了,我想。感谢unutbu给我指点sre_parse
!
import sre_parse
def get_regex_max_match_len(regex):
minlen, maxlen = sre_parse.parse(regex).getwidth()
if maxlen >= sre_parse.MAXREPEAT: raise ValueError('unbounded regex')
return maxlen
Run Code Online (Sandbox Code Playgroud)
结果是:
>>> get_regex_max_match_len('foo((bar){2,3}|potato)')
12
>>> get_regex_max_match_len('.*')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in get_regex_max_match_len
ValueError: unbounded regex
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3035 次 |
最近记录: |