Raja Amer Khan
Raja Amer Khan

Reputation: 1519

How do I shorten this regex?

I would like to allow the string to start with capital letters and the first two characters should not contain NL but other alphabets like DE, BE etc..

Here is how I do it in javascript

str.substring(0,2).match(/^[ABCDEFGHIJKLMOPQRSTUVWXYZ]+[ABCDEFGHIJKMNOPQRSTUVWXYZ]+$/)

I would like to shorten it to ranges. I tried with these range expressions [A-MO-Z], [A-M][O-Z]+ but non of them work.

Edit: I tried these expressions but they don't work

str.substring(0,2).match(/^[A-MO-Z]+[A-KM-Z]+$/)
str.substring(0,2).match(/^[A-M][O-Z]+[A-K][M-Z]+$/)
str.substring(0,2).match(/^([A-M][O-Z])+([A-K][M-Z])+$/)

Upvotes: 0

Views: 66

Answers (1)

Paul
Paul

Reputation: 141829

That's a prime use case for a negative look ahead:

str.match(/^(?!NL)[A-Z]{2}/)

Note that this will allow NA, NB, NC, ... and AL, BL, CL, ..., just not NL specifically.

Upvotes: 5

Related Questions