Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

regex

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, I gather it has to do with how I am writing my regular expression. Any help would be appreciated.

private static bool isValid(String str)
{
    bool valid = false;

    Regex reg = new Regex((@"a-zA-Z+"));

    if (reg.Match(str).Success)
        valid = false;
    else 
        valid  = true;     

     return valid;
}
like image 585
Sophie Ker Avatar asked May 16 '11 12:05

Sophie Ker


2 Answers

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.
like image 60
Daniel Hilgarth Avatar answered Oct 23 '22 06:10

Daniel Hilgarth


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

like image 43
VikciaR Avatar answered Oct 23 '22 04:10

VikciaR