我有一个输入字符串,我想验证它包含:

仅限信件或 只有字母和数字或者 只能使用字母、数字或下划线

为了澄清,我在代码中有3种不同的情况,每种情况调用不同的验证。用c#实现这个最简单的方法是什么?


当前回答

只有字母:

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

仅限字母和数字:

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

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

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

其他回答

迭代通过字符串字符和使用'Char'函数称为'IsLetter'和'IsDigit'。

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

如果你是一个新手,那么你可以参考我的代码..我所做的就是开一张支票,这样我就只能得到字母和空白!您可以在第二个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();
       }

只有字母:

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

仅限字母和数字:

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

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

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

我认为这是一个使用正则表达式的好情况:

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

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