Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 正则表达式忽略负查找和匹配之间的所有内容_Python_Regex_Python 3.x - Fatal编程技术网

Python 正则表达式忽略负查找和匹配之间的所有内容

Python 正则表达式忽略负查找和匹配之间的所有内容,python,regex,python-3.x,Python,Regex,Python 3.x,我知道几乎每一个正则表达式问题都必须被问到和回答,但我想: 我想要一个正则表达式来匹配: "alcohol abuse" "etoh abuse" "alcohol dependence" "etoh dependence" 但不匹配 "denies alcohol dependence" "denies smoking and etoh dependence" "denies [anything at all] and etoh abuse" 消极的回顾是显而易见的,但是我怎么能不匹配最后

我知道几乎每一个正则表达式问题都必须被问到和回答,但我想:

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

"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)")
re.compile((?您可以利用并采用以下通用模式:

bad |(good)

实际上,您确实首先匹配了您不想要的部分,但在替换的最后一部分中只记住了“好”部分

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

拒绝。*(?:(?:酒精|依附性))s*((?:酒精|依附性))s*((?:酒精|依附性))


此处的“组1”仅保存有效匹配项。

如果无法安装任何模块,可以重新格式化表达式并检查组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

如果您有超过
个拒绝
(即
不喜欢…
),只需更改第一个标题组。

是附加模块(即
正则表达式
,它支持无限查找)允许?我在一个不会安装的VM中工作,但如果
re
中没有解决方案,我会完全安装它。如果可能的话,在
re
中这将是令人惊讶的是,对于PyPi regex模块,您可以使用
(?),但是-具体取决于您需要什么(提取或替换)-你也可以使用
re
解决问题。事实上,我只是简单地将匹配的事实用在一些条件逻辑中。不需要提取或替换。不过,感谢regex提示,我不知道该模块。遗憾的是,我无法控制VM。我不够可靠,无法自己安装软件包。sigh@WoodyPride作为一种解决方法,您可以匹配反转的字符串,并使用反转模式的负前瞻:
r'(ecnedneped | esuba)\s*(hote | lohocla)(?!.*seined)
。这太棒了。实际上我从来都不知道如何使用这样的匹配组。谢谢!@WoodyPride:很高兴提供帮助!