Skip to main content
 首页 » 编程设计

python之使用负后视的多个正则表达式匹配

2024年10月24日33unruledboy

我有这一段:

"This is the next paragraph that contains the code for the master budget and the other master budget. Also it contains only the master budget terms. But only this budget should get matched. But this budget will not get matched".

在这里,我试图只匹配单词“budget”的第一次出现,如果它前面有“master”或“other master”,则跳过所有出现的 budget。我为此使用了负面回顾,并提出了一段在网站 https://regex101.com 上运行良好的代码。 :

p = re.compile(r'((?<!master|master other)\s\bbudget\b)') 
test_str = "This is the next paragraph that contains the code for the master budget and the other master budget. Also it contains only the master budget terms. But only this budget should get matched" 
re.findall(p, test_str) 

但是我得到这个错误“后视需要固定宽度的模式”。有什么办法解决这个问题吗?

请您参考如下方法:

你得到的错误是因为 Python 中的 lookbehinds 应该是固定长度的,并且 (?<!master|master other)长度不是固定的。

自

(?<!master|master other) 

相当于

(?<!master)(?<!master other) 

您可以将正则表达式更改为:

((?<!master)(?<!master other)\s\bbudget\b)