C# Regex: Checking for “a-z” and “A-Z”

前端 未结 3 1711
南笙
南笙 2020-11-29 10:33

I want to check if a string inputted in a character between a-z or A-Z. Somehow my regular expression doesn\'t seem to pick it up. It always returns true. I am not sure why,

3条回答
  •  情书的邮戳
    2020-11-29 10:53

    The right way would be like so:

    private static bool isValid(String str)
    {
        return Regex.IsMatch(str, @"^[a-zA-Z]+$");
    }
    

    This code has the following benefits:

    • Using the static method instead of creating a new instance every time: The static method caches the regular expression
    • Fixed the regex. It now matches any string that consists of one or more of the characters a-z or A-Z. No other characters are allowed.
    • Much shorter and readable.

提交回复
热议问题