Regex 如何创建与字符串匹配的正则表达式,该字符串包含一个列表中的单词,而不包含另一个列表中的单词?
如何创建与字符串匹配的正则表达式,该字符串包含一个列表中的单词,而不包含另一个列表中的单词 我想创建一个正则表达式,它匹配一个包含以下任意单词(fox,cat)的字符串,而不包含(red,black) 例: 敏捷的棕色狐狸跳过懒狗——火柴 敏捷的红狐跳过了懒狗——没有对手 敏捷的棕色狮子跳过懒猫——火柴 那只敏捷的黑猫跳过了那只懒狗——没有对手 可以用正则表达式吗?试试正则表达式:Regex 如何创建与字符串匹配的正则表达式,该字符串包含一个列表中的单词,而不包含另一个列表中的单词?,regex,regex-negation,regex-lookarounds,regex-group,Regex,Regex Negation,Regex Lookarounds,Regex Group,如何创建与字符串匹配的正则表达式,该字符串包含一个列表中的单词,而不包含另一个列表中的单词 我想创建一个正则表达式,它匹配一个包含以下任意单词(fox,cat)的字符串,而不包含(red,black) 例: 敏捷的棕色狐狸跳过懒狗——火柴 敏捷的红狐跳过了懒狗——没有对手 敏捷的棕色狮子跳过懒猫——火柴 那只敏捷的黑猫跳过了那只懒狗——没有对手 可以用正则表达式吗?试试正则表达式:^(((?!(红色|黑色)))*(?:狐狸|猫)(?:(?!(红色|黑色)))*$ 说明: Non-cap
^(((?!(红色|黑色)))*(?:狐狸|猫)(?:(?!(红色|黑色)))*$
说明:
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)
红色和黑色可以在字符串中的任何位置,例如快速狐狸跳过懒狗黑色-->这不应该匹配