How can I use a regex to tell if a string has 10 digits?

I need to find a regex that tests that an input string contains exactly 10 numeric characters, while still allowing other characters in the string.

I'll be stripping all of the non-numeric characters in post processing, but I need the regex for client-side validation.

For example, these should all match:

  • 1234567890
  • 12-456879x54
  • 321225 -1234AAAA
  • xx1234567890

But these should not:

  • 123456789 (not enough digits)
  • 12345678901 (too many digits)

This seems like it should be very simple, but I just can't figure it out.

Answers


/^\D*(\d\D*){10}$/

Basically, match any number of non-digit characters, followed by a digit followed by any number of non-digit characters, exactly 10 times.


May be a simpler way, but this should do it.

/^([^\d]*\d){10}[^\d]*$/

Though the regex gets easier to handle if you first strip out all non-numeric characters then test on the result. Then it's a simple

/^\d{10}$/

^\D*(\d\D*){10}\D*$

Need Your Help

How to structure mysql table to avoid extra rows

mysql database database-design data-structures

I am maintaining record of expenses an expenses table looks like this

How would I build python myself from source code on Ubuntu?

python linux ubuntu

Ubuntu comes with Python 2.7.2+ pre-installed. (I also downloaded the python dev packages.) Because of another issue I'm having (Explained in extreme depth in How do I replace/update the version of...