12

I want to create a regular expression where only numbers are allowed with max length 9 and no minimum length. I came up with \d{9}[0-9] but it isn't working.

Brad Mace
  • 27,194
  • 17
  • 102
  • 148
t0mcat
  • 5,511
  • 19
  • 45
  • 58

4 Answers4

28

You're close. Try this:

^\d{0,9}$

The ^ and $ match the beginning and the end of the text, respectively. \d{0,9} matches anywhere in the string, so d0000 would pass because it would match the 0000 even though there is a d in it, which I don't think you want. That's why they ^$ should be in there.

vcsjones
  • 138,677
  • 31
  • 291
  • 286
14

Regular expressions can be tricky; what you've written does the following:

  • \d - digit
  • \d{9} - exactly 9 digits
  • \d{9}[0-9] - exactly 9 digits, followed by something between 0 and 9

If you want no minimum limit of length, but a maximum length of 9, you probably want the following regular expression:

  • \d{0,9} - 0 to 9 digits
NT3RP
  • 15,262
  • 9
  • 61
  • 97
4

I think It should be 1 to 9 digits:

^\d{1,9}$
Jan
  • 8,011
  • 3
  • 38
  • 60
2

It looks like you were close, try \d{0,9}.

Brian Fisher
  • 23,519
  • 15
  • 78
  • 82