正则表达式否定匹配

Tje*_*mer 9 javascript regex

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

匹配第4个字符后面的字符不包含"GP"的所有字符串.

一些示例字符串:

  • EDAR - 匹配!
  • EDARGP - 不匹配
  • EDARDTGPRI - 没有比赛
  • ECMRNL - 匹配

我很喜欢一些帮助这里...

Fai*_*Dev 11

使用零宽度断言:

if (subject.match(/^.{4}(?!.*GP)/)) {
    // Successful match
}
Run Code Online (Sandbox Code Playgroud)

说明:

"
^        # 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
)
"
Run Code Online (Sandbox Code Playgroud)


Dan*_*Dan 7

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

/^.{4}(?!.*GP)/
Run Code Online (Sandbox Code Playgroud)

仅当在前四个字符之后GP找不到该字符串时,才匹配.

  • 你赢了比赛.:) +1 (2认同)