正则表达式-排除单词,但带有通配符

时间:2018-07-18 17:23:24

标签: python regex

一个表达式可能无法实现,但是可以了。

txt = 'check from HERE and i need RED but not BLUE'

对于上面的文本,我需要一个表达式,如果“ RED”出现在“ HERE”之后任何地方,但是“ BLUE”没有出现在此处任何地方,则该表达式将匹配。 / p>

1 个答案:

答案 0 :(得分:2)

对于后代:

没有正则表达式

txt = 'check from HERE and i need RED but not BLUE'
after_here = txt.split('HERE', 1)[1]
result = red in after_here and blue not in after_here

正则表达式

^.*HERE(?!.*BLUE.*).*RED.*$
#   ^ look after 'HERE'
#           ^ negative lookahead in everything that comes after HEAD for BLUE
#                     ^ look for RED in everything that comes after HEAD

// see https://www.regular-expressions.info/lookaround2.html