Regex to allow only 9 or 10 characters?

9 characters require 2 letters at the beginning ie ab1234567, and 10 characters must have all digits i, e 1234567890. How to do this using regular expression?

Here is what I have tried.

/^[a-zA-Z]{2}[\d]{7}|[\d]{10}$/ 

This does not work. I would really appreciate your help.

+6
source share
2 answers

| in your regular expression allows it to match either of these two possibilities:

 ^[a-zA-Z]{2}[\d]{7} [\d]{10}$ 

That is, the beginning of the line, then 2 letters and seven numbers, followed by something, or something, followed by 10 numbers and the end of the line. Try the following:

 /^([a-zA-Z]{2}\d{7}|\d{10})$/ 

(Note that I removed [] from each \d - it makes no sense to have a character class with one character in it.)

+10
source

The problem is that ^ uses only the first option, and $ only applies to the second.

Try the following:

 /^(?:[az]{2}\d{7}|\d{10})$/i 
+8
source

All Articles