Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 709
JeffK Avatar asked Jan 06 '10 20:01

JeffK


People also ask

How do you check if a string contains only numbers regex?

To check if a string contains only numbers in JavaScript, call the test() method on this regular expression: ^\d+$ . The test() method will return true if the string contains only numbers. Otherwise, it will return false . The RegExp test() method searches for a match between a regular expression and a string.

Which regex matches one or more digits Python?

You can use out\dmf\d+ , or, if you want to match only 1 or 2 digits at the end, out\dmf\d{1,2} .

How do you get a number from a string in regex?

Python Regex – Get List of all Numbers from String. To get the list of all numbers in a String, use the regular expression '[0-9]+' with re. findall() method. [0-9] represents a regular expression to match a single digit in the string.


1 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.

like image 58
Amber Avatar answered Nov 05 '22 07:11

Amber