19

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;
}
2
  • 2
    You're setting it to false after it matches.
    – Jeff LaFay
    May 16, 2011 at 13:03
  • A TIP: Rather than writing a-zA-Z you can use ?i to make your regex pattern case insensitive and then just write a-zwhere ever required. Nov 12, 2012 at 13:02

4 Answers 4

25
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
24

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.
1
  • Because of the anchors ^ and $, ^[a-zA-Z]+$ will match a string if it is entirely composed of letters (probably what the OT intends, but you should update the explanation). May 16, 2011 at 13:10
7

Use

Regex.IsMatch(@"^[a-zA-Z]+$");
0

Update in .NET 7 (Nov 2022+)

There is a new method called Char.IsAsciiLetter which will:

determine whether the character is in the range 'A' through 'Z', inclusive, or 'a' through 'z', inclusive.

If you want to test that a string has any english letters, you can use Linq.Any

var hasLetter = "word".Any(Char.IsAsciiLetter); // true

If you want to test that a string has only english letters, you can use Linq.All

var allLetters = "word".All(Char.IsAsciiLetter); // true

Generated Regex Source Code

.NET 7 Introduced GeneratedRegex which allows you to parse and compile regex statements at compile time, but also allows you to inspect any optimizations done under the hood. If you want to see how the regex string [a-zA-Z] is actually implemented, you can add the following to any dotnet 7 project

public static partial class RegexExtensions
{
    [GeneratedRegex("[a-zA-Z]")]
    public static partial Regex HasLetter();
}

And then view source on the generated code. You'll see that even if you use regex as performantly as possible, it'll just use the exact same method on the char class anyway under the hood:

"[a-zA-Z]" regex source code

Performance Benchmarks

According to benchmark tests, the fastest way to check if a string contains an english letter is to use a for loop with Char.IsAsciiLetter:

Has a-z benchmarks

Polyfill

If you're not on .NET 7 yet, you can look at how the method is implemented for a performance-aware implementation:

public static bool IsAsciiLetter(char c) => (uint)((c | 0x20) - 'a') <= 'z' - 'a';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.