【发布时间】:2021-06-15 06:07:33
【问题描述】:
我已经在这个问题上坐了几个小时了,我真的不知道了...... 本质上,我有一个 A|B|C - 类型分隔的正则表达式,无论出于何种原因,C 都与 B 匹配,即使单个正则表达式应该从左到右进行测试并以非贪婪的方式停止(即一次匹配找到,其他正则表达式'不再测试)。
这是我的代码:
text = 'Patients with end stage heart failure fall into stage D of the ABCD classification of the American College of Cardiology (ACC)/American Heart Association (AHA), and class III–IV of the New York Heart Association (NYHA) functional classification; they are characterised by advanced structural heart disease and pronounced symptoms of heart failure at rest or upon minimal physical exertion, despite maximal medical treatment according to current guidelines.'
expansion = "American Heart Association"
re_exp = re.compile(expansion + "|" + r"(?<=\W)" + expansion + "|"\
+ expansion.split()[0] + r"[-\s].*?\s*?" + expansion.split()[-1])
m = re_exp.search(text)
print(m.group(0))
我希望正则表达式找到“扩展”字符串。在我的数据集中,有时文本对扩展字符串进行了略微编辑,例如在主要名词之间有冠词或介词,如“for”或“the”。这就是为什么我首先尝试按原样匹配字符串,然后尝试匹配它是否在任何非单词字符之后(即括号,或者像上面的示例一样,因为空格被省略了很多东西)最后,我只是通过使用通配符搜索字符串的开头和结尾来查找字符串。
不管怎样,对于上面的例子,我希望得到以下输出:
American Heart Association
但我得到的是
American College of Cardiology (ACC)/American Heart Association
这是最终正则表达式的匹配项。
如果我删除最终的正则表达式或只是调用re.findall(r"(?<=\W)"+ expansion, text),我会得到我想要的输出,这意味着正则表达式实际上匹配正确。
什么给了?
【问题讨论】:
-
这是你的模式
American Heart Association|(?<=\W)American Heart Association|American[-\s].*?\s*?Association见regex101.com/r/vzN62o/1。正则表达式从左到右,替代方案从左到右尝试。当遇到单词American的第一次出现时,前 2 个选项不匹配,而第 3 个选项匹配,这就是你得到匹配项的原因 -
而不是使用
.*?,例如,您可以不允许匹配\bAmerican\b[^/,.]*\bAssociation\bregex101.com/r/Iz83Xb/1之间的指定字符或像\bAmerican\b(?:(?!American|Association).)*\bHeart Associationregex101.com/r/kiR7xx/1这样的缓和贪婪令牌