简体   繁体   中英

Regex match 2 alpha plus 6 digits in C#

I need a regex to match this pattern ( using C# )

My match must start with 2 alpha characters ( MA or CA ) and must end with either 6 or seven numeric digits; such as CA123456 or MA123456 or 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. Afterwards, \\d{6,7} matches either 6 or 7 digits.


The issue with your pattern is the first alternative: ^[MA]{2} matches any string that starts with AA , AM , MA , or MM . 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. This is why

it seems to match most anything.

I believe there are great usages of RegEx; in this particular case, using the built-in string functions of C# may be a better option:

  1. Must start with either MA or CA
  2. Must end with at least 6 digits (if there are 7, then there will be 6 digits)
  3. Combining 1 and 2, the string must be at least 8 characters long

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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