python - 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 版本和不同的机器会导致捕获不同数量的长正则表达式字符串。我仍然无法确定这是否是re
Python 库中的问题、特定于 Python 3 的问题(我没有将其与 Python 2 进行比较)、机器问题、内存问题或其他问题。
我在上面的示例中使用了 Python 3.8.1,并在另一个示例中使用了 Python 3.7.2,使用了详细的正则表达式和其他示例(我不能分享这些示例,因为这些示例是专有的)。
关于 Python 正则表达式引擎的机制以及为什么会发生这种情况的任何帮助(如果有可以通过正则表达式捕获的最大长度,为什么?),这将非常有帮助。
解决方案
您认为repr
匹配的 是匹配的文本。它不是。repr
尝试不为大型匹配转储文本页面。如果您想查看完整匹配的文本,请索引以将其作为字符串获取:
print(re.match(re_pattern_str, sample_paragraph)[0])
#^^^ gets the matched text itself
您可以从中看出repr
它的匹配时间要长得多(它跨越索引 0 到 78)。
推荐阅读
- python - 如何在 mediapipe 中获取面部混搭地标的坐标
- docker - 带有 tmpfs 挂载的 Docker BuildKit 构建第二次失败
- java - Android:在创建和显示 AlertDialog 之前获取资源 ID?
- python - 在 Kafka 中消费消息
- haskell - 带有简单断言的 Haskell 脚本
- javascript - 在解决方案中使用时 css 剪辑路径源 URL 会发生变化
- sql - 我如何在 LIKE 查询 django raw sql 中使用占位符和 %
- amazon-web-services - OpenApi (Swagger) 与 AWS ECS 集成 - 公开所有操作
- r - sarprobit 包中的 sarorderedprobit 函数是否支持面板或时间序列数据集(在 r 内)?
- php - 有没有办法使用 Laravel Eloquent 管理 mysql 用户并在 MySQL 中获取数据库大小?