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: 0123开发者_运维知识库456, 1234567, 0123456789, 123467890
Fail: 123456, 12345678, 123456789A 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). - 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:
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}?
Why not a literal interpretation of what you're looking for:
^\d{7}|\d{10}$
精彩评论