[英]Regular expression for validating numeric values
I current have the following regular expression to accept any numeric value that is seven digits 我目前有以下正则表达式可以接受任何七位数的数值
^\\d{7}
How do I improve it so it will accept numeric values that are seven or ten digits? 如何改进它,使其可以接受七位或十位数字的数值?
Pass: 0123456, 1234567, 0123456789, 123467890 通过:0123456、1234567、0123456789、123467890
Fail: 123456, 12345678, 123456789 失败:123456、12345678、123456789
A simple solution is this: 一个简单的解决方案是这样的:
^\d{7}(\d{3})?$
There are at least two things to note with this solution: 此解决方案至少要注意两件事:
\\d
may match far more than you intended (for example foreign characters that are digits in other non-Latin languages). \\d
可能比您预期的匹配得多(例如,其他非拉丁语言中的数字外来字符)。 (?: ... )
. (?: ... )
来解决此问题。 So for these reasons you may want to use this slightly longer expression instead: 因此,由于这些原因,您可能需要使用稍长的表达式:
^[0-9]{7}(?:[0-9]{3})?$
Here's a little testbed in C# so that you can see it works: 这是C#中的一个小测试平台,因此您可以看到它的工作原理:
for (int i = 0; i < 12; ++i)
{
string input = new string('0', i);
bool isMatch = Regex.IsMatch(input, "^[0-9]{7}(?:[0-9]{3})?$");
Console.WriteLine(i.ToString().PadLeft(2) + ": " + isMatch);
}
Result: 结果:
0: False 1: False 2: False 3: False 4: False 5: False 6: False 7: True 8: False 9: False 10: True 11: False
为什么不对要查找的内容进行字面解释:
^\d{7}|\d{10}$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.