Skip to main content
 首页 » 编程设计

c#之正则表达式不匹配

2024年01月25日24qq78292959

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

我试过这个但不是真的

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

请您参考如下方法:

正则表达式本身看起来基本没问题,当然它也允许 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; 

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