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:
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.