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