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

时间:2018-05-24 15:08:25

标签: regex regex-negation regex-lookarounds regex-group

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

我想创建一个匹配包含以下任何单词(fox,cat)且不包含(红色,黑色)的字符串的正则表达式。

例如:

  

快速的棕色狐狸跳过懒狗---匹配

     

快速的红狐狸跳过懒狗 - 不匹配

     

快速的棕色狮子跳过懒猫 - 匹配

     

快速的黑猫跳过懒狗 - 不匹配

Regex可以吗?

1 个答案:

答案 0 :(得分:0)

尝试正则表达式:^(?:(?!(red|black)).)*(?:fox|cat)(?:(?!(red|black)).)*$

Demo

说明:

    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)