简体   繁体   English

正则表达式在C#中匹配2个字母加上6个数字

[英]Regex match 2 alpha plus 6 digits in C#

I need a regex to match this pattern ( using C# ) 我需要一个regex来匹配此模式(使用C#)

My match must start with 2 alpha characters ( MA or CA ) and must end with either 6 or seven numeric digits; 我的比赛必须以2个字母字符(MA或CA)开头,并且必须以6或7个数字结尾; such as CA123456 or MA123456 or MA1234567 例如CA123456或MA123456或MA1234567

Here is what I tried: 这是我尝试过的:

Regex.IsMatch(StringInput, @"^[MA]{2}|^[CA]{2}\d{6,7}?")) 

Unfortunately, it seems to match most anything 不幸的是,它似乎可以匹配大多数东西

Try this pattern: 试试这个模式:

^[MC]A\d{6,7}$

The leading character class ( [MC] ) requires either an M or a C at the start of the string. 前导字符类( [MC] )在字符串的开头需要MC Afterwards, \\d{6,7} matches either 6 or 7 digits. 之后, \\d{6,7}匹配6或7位数字。


The issue with your pattern is the first alternative: ^[MA]{2} matches any string that starts with AA , AM , MA , or MM . 模式的问题是第一种选择: ^[MA]{2}匹配任何以AAAMMAMM开头的字符串。 It doesn't require any following digits at all. 它根本不需要任何以下数字。 Since the regex engine can match the first alternative for a string like AA1234567 (matching the substring AA ), it doesn't even attempt to find another match. 由于正则表达式引擎可以匹配字符串AA1234567的第一个替代 (匹配子字符串AA ),因此它甚至不会尝试查找其他匹配项。 This is why 这就是为什么

it seems to match most anything. 它似乎可以匹配大多数东西。

I believe there are great usages of RegEx; 我相信RegEx有很多用法。 in this particular case, using the built-in string functions of C# may be a better option: 在这种特殊情况下,使用C#的内置字符串函数可能是一个更好的选择:

  1. Must start with either MA or CA 必须以MA或CA开头
  2. Must end with at least 6 digits (if there are 7, then there will be 6 digits) 必须以至少6位数字结尾(如果有7位数字,那么将有6位数字)
  3. Combining 1 and 2, the string must be at least 8 characters long 组合1和2,字符串必须至少包含8个字符

This would be the string version based on the above rules: 这将是基于上述规则的字符串版本:

public static bool IsValid( string str )
{
    if( str.Length < 8 )
    {
        return false;
    }

    if( !str.StartsWith( "CA" ) && !str.StartsWith( "MA" ) )
    {
        return false;
    }

    int result;
    string end = str.Substring( str.Length - 6 );
    bool isValid = int.TryParse( end, out result );

    return isValid;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM