用于评估字符串的正则表达式,它不包含子字符串' ab'和' cd'为了

时间:2014-10-20 10:01:04

标签: regex

我想构建一个正则表达式来评估一个字符串,该字符串在顺序中不包含两个子字符串" ab"和" cd"

示例:

"This is ab test for cd" <= Not matched because containing "ab", "cd" in order
"This is cd test for ab" <= Matched because containing "ab" and "cd" but not in order
"This is cd test" <= Matched because not containing ab
"This is ab test" <= Matched because not containing cd

2 个答案:

答案 0 :(得分:3)

使用否定先行断言。

^(?!.*\sab\s.*?\scd\b).*

OR

^(?!.*\bab\b.*?\bcd\b).*

DEMO

答案 1 :(得分:1)

^(?!.*?\bab\b.*?\bcd\b)(?!.*?\bcd\b.*?\bab\b).*$

试试这个。看看演示。

http://regex101.com/r/wQ1oW3/30