Regular expression negative match

岁酱吖の 提交于 2021-01-27 02:27:47

问题


I can't seem to figure out how to compose a regular expression (used in Javascript) that does the following:

Match all strings where the characters after the 4th character do not contain "GP".

Some example strings:

  • EDAR - match!
  • EDARGP - no match
  • EDARDTGPRI - no match
  • ECMRNL - match

I'd love some help here...


回答1:


Use zero-width assertions:

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

Explanation:

"
^        # 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
)
"



回答2:


You can use what's called a negative lookahead assertion here. It looks into the string ahead of the location and matches only if the pattern contained is /not/ found. Here is an example regular expression:

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

This matches only if, after the first four characters, the string GP is not found.




回答3:


could do something like this:

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

test will return true for matches and false for non.



来源:https://stackoverflow.com/questions/8408152/regular-expression-negative-match

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!