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.
我需要找到一个正则表达式来测试输入字符串是否包含10个数字字符,同时仍然允许字符串中的其他字符。
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)
123456789(数字不够)
12345678901(数字太多)
This seems like it should be very simple, but I just can't figure it out.
这看起来应该很简单,但我无法弄明白。
3 个解决方案
#1
13
/^\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.
基本上,匹配任意数量的非数字字符,后跟一个数字,后跟任意数量的非数字字符,恰好是10次。
#2
0
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}$/
#3
0
^\D*(\d\D*){10}\D*$
#1
13
/^\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.
基本上,匹配任意数量的非数字字符,后跟一个数字,后跟任意数量的非数字字符,恰好是10次。
#2
0
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}$/
#3
0
^\D*(\d\D*){10}\D*$