JeffK
JeffK

Reputation: 3039

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:

But these should not:

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

Upvotes: 7

Views: 5406

Answers (3)

Antony Hatchkins
Antony Hatchkins

Reputation: 33974

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

Upvotes: 0

Amber
Amber

Reputation: 526573

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

Upvotes: 15

James Maroney
James Maroney

Reputation: 3256

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}$/

Upvotes: 0

Related Questions