正则表达式否定匹配

时间:2011-12-06 23:01:21

标签: javascript regex

我似乎无法弄清楚如何编写执行以下操作的正则表达式(在Javascript中使用):

匹配第4个字符后面的字符不包含“GP”的所有字符串。

一些示例字符串:

  • EDAR - 匹配!
  • EDARGP - 不匹配
  • EDARDTGPRI - 不匹配
  • ECMRNL - 匹配

我在这里一些帮助...

3 个答案:

答案 0 :(得分:11)

使用零宽度断言:

if (subject.match(/^.{4}(?!.*GP)/)) {
    // Successful match
}

<强>解释

"
^        # Assert position at the beginning of the string
.        # Match any single character that is not a line break character
   {4}   # Exactly 4 times
(?!      # Assert that it is impossible to match the regex below starting at this position (negative lookahead)
   .     # Match any single character that is not a line break character
      *  # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
   GP    # Match the characters “GP” literally
)
"

答案 1 :(得分:7)

你可以在这里使用所谓的否定先行断言。它会查看位置前面的字符串,并且只有在包含的模式是/ not / found时才匹配。这是一个正则表达式示例:

/^.{4}(?!.*GP)/

只有在前四个字符之后找不到字符串GP时才匹配。

答案 2 :(得分:2)

可以这样做:

var str = "EDARDTGPRI";
var test = !(/GP/.test(str.substr(4)));

test将为匹配返回true,对非non返回false。