> import regex >>> regex.findall(r"(?be)(mazda2 sta-6ren">
gpt4 book ai didi

使用 or 运算符时,Python 正则表达式的模糊搜索不会返回所有匹配项

转载 作者:太空宇宙 更新时间:2023-11-03 19:43:15 24 4
gpt4 key购买 nike

例如,当我使用时

regex.findall(r"(?e)(mazda2 standard){e<=1}", "mazda 2 standard")

,答案照常是['mazda 2 standard']。

但是当我使用时

regex.findall(r"(?e)(mazda2 standard|mazda 2){e<=1}", "mazda 2 standard")

regex.findall(r"(?e)(mazda2 standard|mazda 2){e<=1}", "mazda 2 standard", overlapped=True)

,输出根本不包含“mazda 2 standard”。如何使输出也包含“mazda 2 standard”?

最佳答案

参见PyPi regex documentation :

By default, fuzzy matching searches for the first match that meets the given constraints. The ENHANCEMATCH flag will cause it to attempt to improve the fit (i.e. reduce the number of errors) of the match that it has found.

The BESTMATCH flag will make it search for the best match instead.

您通过代码获得 mazda 2,因为此匹配不包含错误。

因此,请使用 BESTMATCH 标志(内联修饰符选项是 (?b)):

>>> import regex
>>> regex.findall(r"(?be)(mazda2 standard|mazda 2){e<=1}", "mazda 2 standard")
['mazda 2 standard']
>>>

关于使用 or 运算符时,Python 正则表达式的模糊搜索不会返回所有匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60309091/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com