Python regex match, but exclude if regex match

Question:

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.

Asked By: sebastianwth

||

Answers:

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

^(?!.*borangeb).*bprodb.*$

Demo

Answered By: Tim Biegeleisen
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.