Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a regular expression to accept not more than 10 digits?

How do I create a regular expression to accept not more than 10 digits?

thanks

like image 928
user92027 Avatar asked Jun 23 '09 14:06

user92027


People also ask

How do you limit the length of a regular expression?

By combining the interval quantifier with the surrounding start- and end-of-string anchors, the regex will fail to match if the subject text's length falls outside the desired range.

What does 9 mean in regex?

What does 9 mean in regex? In a regular expression, if you have [a-z] then it matches any lowercase letter. [0-9] matches any digit. So if you have [a-z0-9], then it matches any lowercase letter or digit.

Which regex matches one or more digits?

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


2 Answers

Since you've asked "how", I'll try to explain step by step. Because you did not specify which regexp flavor you are using, so I'll provide examples in PCRE and two POSIX regexp variants.

For simple cases like this you should think of regular expression as of automation, accepting one character at a time, and saying whenever it is valid one (accepting the character) or not. And after each character you can specify quantifiers how many times it may appear, like (in PCRE dialect) * (zero or more times), + (one or more time) or {n,m} (from n to m times). Then the construction process becomes simple:

PRCE  | B.POSIX | E.POSIX   | Comments
------+---------+-----------+--------------------------------------------------
^     | ^       | ^         | Unless you are going to accept anything with 10
      |         |           | digits in it, you need to match start of data;
\d    | [0-9]   | [:digit:] | You need to match digits;
{1,10}| \{1,10\}| {1,10}    | You have to specify there is from 1 to 10 of them.
      |         |           | If you also wish to accept empty string — use 0;
$     | $       | $         | Then, data should end (unless see above).

So, the result is ^\d{1,10}$, ^[0-9]\{1,10}\$ or ^[:digit:]{1,10}$ respectively.

like image 174
drdaeman Avatar answered Oct 14 '22 17:10

drdaeman


^\d{1,9}$

That will match anything from 1 digit to 9.

Since you didn't specify the regex flavor you're working with, that should get you where you need to be. If not, tell us which regex technology you're using.

like image 40
brettkelly Avatar answered Oct 14 '22 16:10

brettkelly