Python中的可变宽度后向问题 [英] Variable-Width Lookbehind Issue in Python
本文介绍了Python中的可变宽度后向问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到以下情况:
1) car on the right shoulder
2) car on the left shoulder
3) car on the shoulder
我想在不存在left | right的情况下匹配"shoulder".因此只有3)返回肩膀"
I want to match "shoulder" when left|right is not present. So only 3) return "shoulder"
re.compile(r'(?<!right|right\s*)shoulder')
sre_constants.error: look-behind requires fixed-width pattern
似乎我不能使用\ s *和"|"
It seems like I can't use \s* and "|"
我该如何解决.
提前谢谢!
推荐答案
regex
模块:可变宽度后视
除了HamZa的答案之外,对于Python中任何复杂的正则表达式,我建议使用出色的regex
模块.它支持无限查找-这种功能的少数引擎之一,以及.NET和JGSoft.
regex
module: variable-width lookbehind
In addition to the answer by HamZa, for any regex of any complexity in Python, I recommend using the outstanding regex
module by Matthew Barnett. It supports infinite looknehind—one of the few engines to do so, along with .NET and JGSoft.
这使您可以执行以下操作:
This allows you to do for instance:
import regex
if regex.search("(?<!right |left )shoulder", "left shoulder"):
print("It matches!")
else:
print("Nah... No match.")
如果愿意,您也可以使用\s+
.
You could also use \s+
if you wished.
输出:
It matches!
这篇关于Python中的可变宽度后向问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文