gpt4 book ai didi

python - Python 中的可变宽度后视问题

转载 作者:太空狗 更新时间:2023-10-29 20:37:10 24 4
gpt4 key购买 nike

我得到了以下场景:

1) car on the right shoulder
2) car on the left shoulder
3) car on the shoulder

当 left|right 不存在时,我想匹配“shoulder”。所以只有 3) 返回“肩膀”

re.compile(r'(?<!right|right\s*)shoulder')
sre_constants.error: look-behind requires fixed-width pattern

看来我不能使用\s* 和 "|"

我该如何解决。

提前致谢!

最佳答案

regex 模块:可变宽度回顾

除了answer by HamZa ,对于 Python 中任何复杂的正则表达式,我建议使用出色的 regex module by Matthew Barnett .它支持无限后视 — 少数支持此功能的引擎之一,还有 .NET 和 JGSoft。

例如,这允许您执行以下操作:

import regex
if regex.search("(?<!right |left )shoulder", "left shoulder"):
print("It matches!")
else:
print("Nah... No match.")

如果您愿意,您也可以使用 \s+

输出:

It matches!

关于python - Python 中的可变宽度后视问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24987403/

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