How do I create a regular expression to accept not more than 10 digits?
thanks
How do I create a regular expression to accept not more than 10 digits?
thanks
/\D\d{0,10}\D/
(assuming "less than" includes 0)
/\D\d{1,10}\D/
(if you want from 1 to 10 digits)
^\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.
for "less than 10" and at least 1 you'd want, assuming it's the only value...
^\d{1,9}$
This will find at least one and no more than 9 digits in a row:
\d{1,9}
Since you've asked "how", I'll try to explain step by stem. 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.
but I'd suggest to divide concerns here, just check if the length of the string is <=10 characters after the input, you don't need regex to do that.