The following regex will match the range 9-11 digits: /\d{9,11}/
What is the best way to write a regex matching exactly 9 or 11 digits (excluding 10)?
Using the pattern attribute of an input element, thus the regex should match the entire value of the input field. I want to accept any number containing 9 or 11 digits.
match(/(\d{5})/g);
Occurrence Indicators (or Repetition Operators): +: one or more ( 1+ ), e.g., [0-9]+ matches one or more digits such as '123' , '000' . *: zero or more ( 0+ ), e.g., [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string.
Definition and Usage. The [0-9] expression is used to find any character between the brackets. The digits inside the brackets can be any numbers or span of numbers from 0 to 9. Tip: Use the [^0-9] expression to find any character that is NOT a digit.
Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.
Well, you could try something like:
^\d{9}(\d{2})?$
This matches exactly nine digits followed by an optional extra-two-digits (i.e., 9 or 11 digits).
Alternatively,
^(\d{9}|\d{11})$
may work as well.
But remember that not everything necessarily has to be done with regular expressions. It may be just as easy to check the string matches ^\d*$
and that the string length itself is either 9 or 11 (using something like strlen
, for example).
This regex would do
^(\d{9}|\d{11})$
or if you dont want to match it exactly
\D(\d{9}|\d{11})\D
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With