简体   繁体   English

Python 正则表达式匹配,但如果正则表达式匹配则排除

[英]Python regex match, but exclude if regex match

I'm trying to write a regex for re.search that can match a string as long as the word prod exists anywhere in the text ( .*prod.* ).我正在尝试为 re.search 编写一个正则表达式,它可以匹配一个字符串,只要单词prod存在于文本中的任何位置( .*prod.* )。 however, it should fail the match if the string should have the word orange anywhere in it.但是,如果字符串中的任何位置都包含orange一词,则匹配失败。

  • web-prod-green # should match web-prod-green # 应该匹配
  • web-prod-orange # should fail to match web-prod-orange # 应该匹配失败
  • web-orange-green # should fail to match web-orange-green # 应该匹配失败
  • orange-prod-green # should fail to match orange-prod-green # 应该匹配失败

How can i do this?我怎样才能做到这一点? Thanks.谢谢。

We could use a negative lookahead to exclude the presence of orange :我们可以使用否定前瞻来排除orange的存在:

^(?!.*\borange\b).*\bprod\b.*$

Demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM