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

I need to find a regex that checks that the input string contains exactly 10 numeric characters, while other characters in the string are still allowed.

I will strip all non-numeric characters in post-processing, but I need a regular expression to validate on the client side.

For example, they should all match:

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

But this should not:

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

It seems to be very simple, but I just can't understand.

+4
source share
3 answers
/^\D*(\d\D*){10}$/ 

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

+13
source

It might be easier, but that should do it.

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

Although the regular expression becomes easier to handle, if you cross out all non-numeric characters first, then check the result. Then it's simple

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

All Articles