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

### Question:

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

thanks

### Solution:1

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.

### Solution:2

``^\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.

### Solution:3

`/\D\d{0,10}\D/` (assuming "less than" includes 0)

`/\D\d{1,10}\D/` (if you want from 1 to 10 digits)

### Solution:4

In Perl:

``^\d{,9}\$  ``

perldoc perlretut is a nice tutorial on regular expressions in Perl.

### Solution:5

I think this would do the trick:

^\d{1,10}\$

### Solution:6

/\D\d{,9}\D/ in Perl

### Solution:7

for "less than 10" and at least 1 you'd want, assuming it's the only value...

``^\d{1,9}\$  ``

### Solution:8

This will find at least one and no more than 9 digits in a row:

`\d{1,9}`

### Solution:9

have a play around with http://gskinner.com/RegExr/

### Solution:10

http://www.regexbuddy.com/

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.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »