[c#] Verifying that a string contains only letters in C#

I have an input string and I want to verify that it contains:

  • Only letters or
  • Only letters and numbers or
  • Only letters, numbers or underscore

To clarify, I have 3 different cases in the code, each calling for different validation. What's the simplest way to achieve this in C#?

This question is related to c# string

The answer is


bool result = input.All(Char.IsLetter);

bool result = input.All(Char.IsLetterOrDigit);

bool result = input.All(c=>Char.IsLetterOrDigit(c) || c=='_');

Letters only:

Regex.IsMatch(theString, @"^[\p{L}]+$");

Letters and numbers:

Regex.IsMatch(theString, @"^[\p{L}\p{N}]+$");

Letters, numbers and underscore:

Regex.IsMatch(theString, @"^[\w]+$");

Note, these patterns also match international characters (as opposed to using the a-z construct).


If You are a newbie then you can take reference from my code .. what i did was to put on a check so that i could only get the Alphabets and white spaces! You can Repeat the for loop after the second if statement to validate the string again

       bool check = false;

       Console.WriteLine("Please Enter the Name");
       name=Console.ReadLine();

       for (int i = 0; i < name.Length; i++)
       {
           if (name[i]>='a' && name[i]<='z' || name[i]==' ')
           {
               check = true;
           }
           else
           {
               check = false;
               break;
           }

       }

       if (check==false)
       {
           Console.WriteLine("Enter Valid Value");
           name = Console.ReadLine();
       }

Please find the method to validate if char is letter, number or space, otherwise attach underscore (Be free to modified according your needs)

public String CleanStringToLettersNumbers(String data)
{
    var result = String.Empty;

    foreach (var item in data)
    {
        var c = '_';

        if ((int)item >= 97 && (int)item <= 122 ||
            (int)item >= 65 && (int)item <= 90 ||
            (int)item >= 48 && (int)item <= 57 ||
            (int)item == 32)
        {
            c = item;
        }

        result = result + c;
    }

    return result;
}

For those of you who would rather not go with Regex and are on the .NET 2.0 Framework (AKA no LINQ):

Only Letters:

public static bool IsAllLetters(string s)
{
    foreach (char c in s)
    {
        if (!Char.IsLetter(c))
            return false;
    }
    return true;
}

Only Numbers:

    public static bool IsAllDigits(string s)
    {
        foreach (char c in s)
        {
            if (!Char.IsDigit(c))
                return false;
        }
        return true;
    }

Only Numbers Or Letters:

    public static bool IsAllLettersOrDigits(string s)
    {
        foreach (char c in s)
        {
            if (!Char.IsLetterOrDigit(c))
                return false;
        }
        return true;
    }

Only Numbers Or Letters Or Underscores:

    public static bool IsAllLettersOrDigitsOrUnderscores(string s)
    {
        foreach (char c in s)
        {
            if (!Char.IsLetterOrDigit(c) && c != '_')
                return false;
        }
        return true;
    }

You can loop on the chars of string and check using the Char Method IsLetter but you can also do a trick using String method IndexOfAny to search other charaters that are not suppose to be in the string.


Recently, I made performance improvements for a function that checks letters in a string with the help of this page.

I figured out that the Solutions with regex are 30 times slower than the ones with the Char.IsLetterOrDigit check.

We were not sure that those Letters or Digits include and we were in need of only Latin characters so implemented our function based on the decompiled version of Char.IsLetterOrDigit function.

Here is our solution:

internal static bool CheckAllowedChars(char uc)
    {
        switch (uc)
        {
            case '-':
            case '.':
            case 'A':
            case 'B':
            case 'C':
            case 'D':
            case 'E':
            case 'F':
            case 'G':
            case 'H':
            case 'I':
            case 'J':
            case 'K':
            case 'L':
            case 'M':
            case 'N':
            case 'O':
            case 'P':
            case 'Q':
            case 'R':
            case 'S':
            case 'T':
            case 'U':
            case 'V':
            case 'W':
            case 'X':
            case 'Y':
            case 'Z':
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                return true;
            default:
                return false;
        }
    }

And the usage is like this:

 if( logicalId.All(c => CheckAllowedChars(c)))
 { // Do your stuff here.. }

Iterate through strings characters and use functions of 'Char' called 'IsLetter' and 'IsDigit'.

If you need something more specific - use Regex class.


I think is a good case to use Regular Expressions:

public bool IsAlpha(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z]+$");
}

public bool IsAlphaNumeric(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z0-9]+$");
}

public bool IsAlphaNumericWithUnderscore(string input)
{
    return Regex.IsMatch(input, "^[a-zA-Z0-9_]+$");
}