regex忽略了负lookback和match之间的所有内容

2024-04-29 09:49:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道几乎每一个regex问题都必须被问到和回答,但我要说的是:

我想要一个正则表达式来匹配:

"alcohol abuse"
"etoh abuse"
"alcohol dependence"
"etoh dependence"

但不匹配

"denies alcohol dependence"
"denies smoking and etoh dependence"
"denies [anything at all] and etoh abuse"

消极的回头看是显而易见的,但我怎么能不匹配最后两个例子呢?你知道吗

到目前为止,我的正则表达式是这样的:

re.compile("(?<!denies\s)(alcohol|etoh)\s*(abuse|dependence)")

我不能在负lookback中包含贪心运算符,因为该运算符只适用于要计算的固定长度字符串。你知道吗

我更愿意一步一个脚印地完成这项工作,因为它将一个正则表达式作为参数输入到一个函数中。你知道吗

谢谢你的提示


Tags: andre运算符allat例子regexdependence
2条回答

如果无法安装任何模块,可以重新格式化表达式并检查组1是否为空:

import re
rx = re.compile("(denies)?.*?(alcohol|etoh)\s*(abuse|dependence)")

sentences = ["alcohol abuse", "etoh abuse", "alcohol dependence", "etoh dependence",
             "denies alcohol dependence", "denies smoking and etoh dependence", "denies [anything at all] and etoh abuse"]

def filterSentences(input):
    m = rx.search(input)
    if m and m.group(1) is None:
        print("Yup: " + sent)

for sent in sentences:
    filterSentences(sent)

这就产生了

Yup: alcohol abuse
Yup: etoh abuse
Yup: alcohol dependence
Yup: etoh dependence

如果有超过denies(即does not like...),只需更改第一个标题组。你知道吗

您可以使用match groups并采用以下常规模式:

bad|(good)

你确实首先匹配了你不想要的部分,但是在替换的最后一部分只记住了“好”部分。你知道吗

因此,您的模式将是(请注意所有“仅分组”括号):

denies.*?(?:(?:alcohol|etoh)\s*(?:abuse|dependence))|((?:alcohol|etoh)\s*(?:abuse|dependence))

regex101 demo中的“组1”仅包含有效匹配项。你知道吗

相关问题 更多 >