【发布时间】:2021-05-25 19:23:10
【问题描述】:
我正在尝试在 python 中使用正则表达式匹配以下内容(re 模块):
"...milk..." => matched ['milk']
"...almondmilk..." = no match
"...almond milk..." = no match
"...almond word(s) milk..." => matched ['milk']
"...almondword(s)milk..." => matched ['milk']
"...soymilk..." = no match
"...soy milk..." = no match
"...soy word(s) milk..." => matched ['milk']
"...soyword(s)milk..." => matched ['milk']
我的另一个要求是找到给定字符串中的所有匹配项。所以我使用re.findall()
我使用question 的答案(并查看了许多其他 SO 页面)来构建我的正则表达式:
regx = '^(?!.*(soy|almond))(?=$|.*(milk)).*'
但是当我用一个简单的例子测试它时,我得到了不正确的行为:
>>> food = "is combined with creamy soy and milk. a fruity and refreshing sip of spring, "
>>> re.findall(regx, food)
[]
>>> food = "is combined with creamy milk. a fruity and refreshing sip of spring, "
>>> re.findall(regx, food)
[('', 'milk')]
这两个都应该只返回['milk']。另外,如果我有多个牛奶实例,我只会得到一个结果而不是两个:
>>> food = "is combined with creamy milk. a fruity and refreshing sip of milk, "
>>> re.findall(regx, food)
[('', 'milk')]
我在我的正则表达式中做错了什么,我应该如何调整它来解决这个问题?
【问题讨论】:
-
也许
(?<!soy)(?<!soy )(?<!almond)(?<!almond )milk对你有用。 -
我不确定您是否考虑过这一点。那么“......对于杏仁行业。许多牧场主发现牛奶是一种提神饮料。”?那应该匹配吗?如果没有,为什么不呢?
-
@TimRoberts 这是给我还是给 Wiktor 的问题?对于我非常具体的用例,这需要匹配,因为它属于“......杏仁词牛奶......”。其中 word(s) 是任意数量的单词。