Match everything except for specified strings

前端 未结 7 1765
名媛妹妹
名媛妹妹 2020-11-22 14:25

I know that the following regex will match \"red\", \"green\", or \"blue\".

red|green|blue

Is there a straightforward way of making it mat

7条回答
  •  渐次进展
    2020-11-22 14:53

    If you want to make sure that the string is neither red, green nor blue, caskey's answer is it. What is often wanted, however, is to make sure that the line does not contain red, green or blue anywhere in it. For that, anchor the regular expression with ^ and include .* in the negative lookahead:

    ^(?!.*(red|green|blue))
    

    Also, suppose that you want lines containing the word "engine" but without any of those colors:

    ^(?!.*(red|green|blue)).*engine
    

    You might think you can factor the .* to the head of the regular expression:

    ^.*(?!red|green|blue)engine     # Does not work
    

    but you cannot. You have to have both instances of .* for it to work.

提交回复
热议问题