Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression negative match

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...

like image 443
Tjeerd Kramer Avatar asked Dec 06 '11 23:12

Tjeerd Kramer


1 Answers

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
)
"
like image 90
FailedDev Avatar answered Oct 20 '22 00:10

FailedDev