[Solved] Regex condition in C#


As you further explained that you actually do want to match any letter at the beginning, and any two digits at the end of the string, using a regular expression is indeed the shortest way to solve this.

Regex re = new Regex("^[a-z].*[0-9]{2}$", RegexOptions.IgnoreCase);

Console.WriteLine(re.IsMatch("Apple02")); // true
Console.WriteLine(re.IsMatch("Arrow")); // false
Console.WriteLine(re.IsMatch("45Alty12")); // false
Console.WriteLine(re.IsMatch("Basci98")); // true

Otherwise, if your requirement is simple, e.g. just the letter A or a at the beginning, and 12 or 02 at the end, then you can also solve this easily without regular expressions:

bool Match(string s)
{
    if (string.IsNullOrWhiteSpace(s))
        return false;

    if (s[0] != 'a' && s[0] != 'A')
        return false;

    return s.EndsWith("02") || s.EndsWith("12");
}

Examples:

Console.WriteLine(Match("Apple02")); // true
Console.WriteLine(Match("Arrow")); // false
Console.WriteLine(Match("45Alty12")); // false
Console.WriteLine(Match("a12")); // true
Console.WriteLine(Match("a")); // false
Console.WriteLine(Match("12")); // false

Of course you can also expand this to fit your more complex requirement. In your case, you could use char.IsLetter and char.IsDigit to make the checks:

bool Match(string s)
{
    if (string.IsNullOrWhiteSpace(s))
        return false;

    return s.Length > 2 && char.IsLetter(s[0]) &&
        char.IsDigit(s[s.Length - 1]) && char.IsDigit(s[s.Length - 2]);
}

Note that the IsLetter method also accepts letters from non-English alphabets, so you might need to change that. You could alternatively make a comparison like this:

bool Match(string s)
{
    if (string.IsNullOrWhiteSpace(s))
        return false;

    return s.Length > 2 &&
        ((s[0] >= 'a' && s[0] <= 'z') || (s[0] >= 'A' && s[0] <= 'Z'))
        char.IsDigit(s[s.Length - 1]) && char.IsDigit(s[s.Length - 2]);
}

10

solved Regex condition in C#