views:

107

answers:

3

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.

A: 

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}$/
James Maroney
matches 1234567890a1
Antony Hatchkins
+7  A: 
/^\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.

Amber
Thanks. This works for my test cases, but I confess that I don't understand it. I understand that \D is non-numeric, and \d is numeric, ^ and $ are the start and end, respectively, and that {10} says exactly 10 times. So, while I get all of the symbology, I just don't get the magic behind the curtain. I see some other comments here about matching across multi-lines, but since I'm validating a single-line textbox, this one will do the job.
JeffK
Actually, I just read the description you'd already written. That makes perfect sense.
JeffK
A: 
^\D*(\d\D*){10}\D*$
Antony Hatchkins
The extra `\D*` on the end is unnecessary. Anything non-digit at the end will get picked up as part of the 10th capture group.
Amber
yep, agree, editing the post will result in your variant :)
Antony Hatchkins