验证字符串是否只包含 C# 中的字母

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1181419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:12:48  来源:igfitidea点击:

Verifying that a string contains only letters in C#

c#string

提问by Bab Yogoo

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#?

澄清一下,我在代码中有 3 种不同的情况,每种情况都需要不同的验证。在 C# 中实现这一目标的最简单方法是什么?

采纳答案by Philippe Leybaert

Only letters:

只有字母:

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

Only letters and numbers:

只有字母和数字:

Regex.IsMatch(input, @"^[a-zA-Z0-9]+$");

Only letters, numbers and underscore:

只有字母、数字和下划线:

Regex.IsMatch(input, @"^[a-zA-Z0-9_]+$");

回答by Baget

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

您可以循环字符串的字符并使用 Char 方法IsLetter 进行检查, 但您也可以使用 String 方法IndexOfAny来搜索其他不应该出现在字符串中的字符。

回答by Arnis Lapsa

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

遍历字符串字符并使用名为“IsLetter”和“IsDigit”的“Char”函数。

If you need something more specific - use Regex class.

如果您需要更具体的东西 - 使用 Regex 类。

回答by CMS

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_]+$");
}

回答by Fredrik M?rk

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-zconstruct).

请注意,这些模式还匹配国际字符(与使用a-z构造相反)。

回答by Muhammad Hasan Khan

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

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

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

回答by ROFLwTIME

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

对于那些不想使用 Regex 并且使用 .NET 2.0 框架(又名没有 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;
    }

回答by Khyzar Ishaq Kapoor

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

如果您是新手,那么您可以参考我的代码。我所做的是进行检查,以便我只能获得字母和空格!您可以在第二个 if 语句之后重复 for 循环以再次验证字符串

       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();
       }

回答by Ayta? Utku TOPAL

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.

我发现使用正则表达式的解决方案比使用 Char.IsLetterOrDigit 检查的解决方案慢 30 倍。

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.

我们不确定这些字母或数字是否包括在内,我们只需要拉丁字符,因此基于 Char.IsLetterOrDigit 函数的反编译版本实现了我们的函数。

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.. }

回答by Alfred Rojas

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

请找到验证char是字母、数字还是空格的方法,否则附加下划线(可根据需要随意修改)

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;
}