正则表达式不匹配

时间:2011-11-18 09:56:07

标签: c# regex

如何编写RegEx表达式以匹配以090或091或0123或0168或0199或0124开头的数字以及10到11位数之间的长度?

我试试这个但不是真的

@"^(090|091|0123|0168|0199|0124)\d{7,8}$"

1 个答案:

答案 0 :(得分:7)

正则表达式本身看起来很好,当然它也会允许12位数字(一个四位数的开头,然后是8位数字)。为了改变这种情况,我建议:

foundMatch = Regex.IsMatch(subjectString, 
    @"^                       # Start of string
    (?=.{10,11}$)             # Assert 10-11 character length
    0                         # Start with matching a 0
    (?:90|91|123|168|199|124) # then one of the alternatives
    [0-9]*                    # then fill the rest with digits.
    $                         # End of string", 
    RegexOptions.IgnorePatternWhitespace);

如果你想在更长的字符串中找到这样的数字,而不是验证字符串,那么使用

resultString = Regex.Match(subjectString, 
    @"\b                      # Start of number
    (?=[0-9]{10,11}\b)        # Assert 10-11 character length
    0                         # Match 0
    (?:90|91|123|168|199|124) # then one of the alternatives
    [0-9]*                    # then fill the rest with digits
    \b                        # End of number", 
    RegexOptions.IgnorePatternWhitespace).Value;

(假设数字被非字母数字字符包围)。