首页 > 解决方案 > Python正则表达式库是否有最大匹配

问题描述

我已经搜索了网络(也许我在搜索错误的东西),但我有一个很长的正则表达式模式,我想匹配:

前任:

import re

re_pattern_str = r"I want to match this \(this is an example\) regular expression to a giant string"

sample_paragraph = "I want to match this (this is an example) regular expression to a giant string. This is a huge paragraph with a bunch of stuff in it"

print(re.match(re_pattern_str, sample_paragraph))

上述程序的输出如下:

<re.Match object; span=(0, 78), match='I want to match this (this is an example) regular>

如您所见,它被切断并且没有捕获整个字符串。

此外,我注意到使用带有大量注释的详细模式((?x)在 Python 中)捕获的内容更少。这是否意味着可以捕获的数量有限制?我还注意到使用不同的 Python 版本和不同的机器会导致捕获不同数量的长正则表达式字符串。我仍然无法确定这是否是rePython 库中的问题、特定于 Python 3 的问题(我没有将其与 Python 2 进行比较)、机器问题、内存问题或其他问题。

我在上面的示例中使用了 Python 3.8.1,并在另一个示例中使用了 Python 3.7.2,使用了详细的正则表达式和其他示例(我不能分享这些示例,因为这些示例是专有的)。

关于 Python 正则表达式引擎的机制以及为什么会发生这种情况的任何帮助(如果有可以通过正则表达式捕获的最大长度,为什么?),这将非常有帮助。

标签: pythonregexpython-3.x

解决方案


您认为repr匹配的 是匹配的文本。它不是。repr尝试不为大型匹配转储文本页面。如果您想查看完整匹配的文本,请索引以将其作为字符串获取:

print(re.match(re_pattern_str, sample_paragraph)[0])
                                               #^^^ gets the matched text itself

您可以从中看出repr它的匹配时间要长得多(它跨越索引 0 到 78)。


推荐阅读