使用.NET正则表达式,匹配任何字符串正好9位数

Nic*_*ick 2 .net regex

我正在尝试创建一个正则表达式来匹配任何具有9位数的字符串.数字可以存在于字符串中的任何位置.

例如,如果你传递了以下字符串,你会得到一个匹配:123456789 123aeiou456abc789

这些字符串无法提供匹配12345678 1234567890

Mar*_*ers 8

试试这个:

@"^(\D*\d){9}\D*$"
Run Code Online (Sandbox Code Playgroud)

或者使用这个改进的版本.它假定您只想匹配0-9而不是其他语言中代表数字的其他字符.它还使用非捕获组来提高性能:

"^(?:[^0-9]*[0-9]){9}[^0-9]*$"
Run Code Online (Sandbox Code Playgroud)

这是故障的细分:

^        Start of string.
(?:      Start a non-capturing group.
[^0-9]*  Match zero or more non-digits.
[0-9]    Match exactly one digit.
)        Close the group.
{9}      Repeat the group exactly 9 times.
[^0-9]*  Match zero or more non-digits.
$        End of string.

这是一个测试平台:

string regex = "^(?:[^0-9]*[0-9]){9}[^0-9]*$"
string[] tests = {
                     "123456789",
                     "123aeiou456abc789",
                     "12345678",
                     "1234567890"
                 };
foreach (string test in tests)
{
    bool isMatch = Regex.IsMatch(test, regex); 
    Console.WriteLine("{0}: {1}", test, isMatch);
}
Run Code Online (Sandbox Code Playgroud)

结果:

123456789: True
123aeiou456abc789: True
12345678: False
1234567890: False