Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for matching certain numbers of digits

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.

like image 864
Jørgen Avatar asked Nov 01 '12 14:11

Jørgen


People also ask

How does regex Match 5 digits?

match(/(\d{5})/g);

Which regex matches one or more digits?

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.

What is regex for numbers?

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.

What does regex 0 * 1 * 0 * 1 * Mean?

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.


2 Answers

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

like image 182
paxdiablo Avatar answered Sep 22 '22 13:09

paxdiablo


This regex would do

^(\d{9}|\d{11})$ 

or if you dont want to match it exactly

\D(\d{9}|\d{11})\D 
like image 41
Anirudha Avatar answered Sep 24 '22 13:09

Anirudha