Home > Software engineering >  Python regex match, but exclude if regex match
Python regex match, but exclude if regex match

Time:12-12

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.*). however, it should fail the match if the string should have the word orange anywhere in it.

  • web-prod-green # should match
  • web-prod-orange # should fail to match
  • web-orange-green # should fail to match
  • orange-prod-green # should fail to match

How can i do this? Thanks.

CodePudding user response:

We could use a negative lookahead to exclude the presence of orange:

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

Demo

  • Related