简体   繁体   English

用于验证数值的正则表达式

[英]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: 此解决方案至少要注意两件事:

  • In a unicode context \\d may match far more than you intended (for example foreign characters that are digits in other non-Latin languages). 在unicode上下文中, \\d可能比您预期的匹配得多(例如,其他非拉丁语言中的数字外来字符)。
  • This regular expression contains a capturing group. 此正则表达式包含一个捕获组。 You probably don't want that. 您可能不想要那样。 You can fix this by changing it to a non-capturing group (?: ... ) . 您可以通过将其更改为非捕获组(?: ... )来解决此问题。

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

Edit : This is wrong, but I'm going to undelete it and leave it around for reference purposes, since the upvotes suggest people thought it was right. 编辑 :这是错误的,但是我将取消删除它,并留作参考,因为投票建议人们认为它是正确的。 The correct solution is here 正确的解决方案在这里


I think just: 我认为只是:

^\d{7}\d{3}?

为什么不对要查找的内容进行字面解释:

^\d{7}|\d{10}$

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM