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

前端 未结 3 1688
南笙
南笙 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.
    0 讨论(0)
  • 2020-11-29 10:57

    Use

    Regex.IsMatch(@"^[a-zA-Z]+$");
    
    0 讨论(0)
  • 2020-11-29 10:59
    Regex reg = new Regex("^[a-zA-Z]+$");
    
    • ^ start of the string
    • [] character set
    • \+ one time or the more
    • $ end of the string

    ^ and $ needed because you want validate all string, not part of the string

    0 讨论(0)
提交回复
热议问题