user92027
user92027

Reputation: 391

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

Upvotes: 11

Views: 38508

Answers (9)

drdaeman
drdaeman

Reputation: 11471

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.

Upvotes: 31

MadH
MadH

Reputation: 1508

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.

Upvotes: 0

Joseph
Joseph

Reputation: 25513

I think this would do the trick:

^\d{1,10}$

Upvotes: 2

Jeremy Smyth
Jeremy Smyth

Reputation: 23493

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

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

Upvotes: 5

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74202

In Perl:

^\d{,9}$

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

Upvotes: 2

joe
joe

Reputation: 35077

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

Upvotes: 1

Dave Everitt
Dave Everitt

Reputation: 17866

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

\d{1,9}

Upvotes: 0

hugoware
hugoware

Reputation: 36397

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

^\d{1,9}$

Upvotes: 0

brettkelly
brettkelly

Reputation: 28205

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

Upvotes: 7

Related Questions