如何创建匹配字符串的正则表达式包含一个列表中的单词并且不包含来自另一个列表的单词?

How can I create a regex that matches a string contains a word from one list AND does not contains word from another list?

如何创建一个与字符串匹配的regex,该字符串包含一个列表中的单词,而不包含另一个列表中的单词?

我想创建一个regex,它匹配一个包含以下任何单词(fox,cat)且不包含(red,black)的字符串。

前任:

The quick brown fox jumps over the lazy dog --- match

The quick red fox jumps over the lazy dog ---- no match

The quick brown lion jumps over the lazy cat---- match

The quick black cat jumps over the lazy dog ---- no match

有没有可能用regex?


试用regex:^(?:(?!(red|black)).)*(?:fox|cat)(?:(?!(red|black)).)*$

演示

说明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    Non-capturing group (?:(?!(red|black)).)* - Confirms red or black is not present before fox or cat
        Negative Lookahead (?!(red|black)) - Assert that the Regex below does not match
            1st Capturing Group (red|black)
                1st Alternative red - red matches the characters red literally (case sensitive)
                2nd Alternative black - black matches the characters black literally (case sensitive)
        . matches any character (except for line terminators)

    Non-capturing group (?:fox|cat) - confirms fox or cat is present
        1st Alternative fox - fox matches the characters fox literally (case sensitive)
        2nd Alternative cat - cat matches the characters cat literally (case sensitive)

Non-capturing group (?:(?!(red|black)).)* - Confirms red or black is not present after fox or cat
        Negative Lookahead (?!(red|black)) - Assert that the Regex below does not match
            1st Capturing Group (red|black)
                1st Alternative red - red matches the characters red literally (case sensitive)
                2nd Alternative black - black matches the characters black literally (case sensitive)
        . matches any character (except for line terminators)