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

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

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


当前回答

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

其他回答

只信:

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

字母和数字:

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

字母、数字和下划线:

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

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

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

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

我还没有看到使用模式匹配的解决方案:

public static bool ContainsOnlyLetters(this string input)
{
    bool isValid = true;

    for (int i = 0; isValid && i < input.Length; i++)
    {
        isValid &= input[i] is >= 'A' and <= 'Z' or >= 'a' and <= 'z';
    }

    return isValid;
}

或者如果你真的非常讨厌可读的代码:

public static bool ContainsOnlyLetters(this string input)
{
    bool isValid = true;
    for (int i = 0; i < input.Length && (isValid &= input[i] is >= 'A' and <= 'Z' or >= 'a' and <= 'z'); i++);
    return isValid;
}
bool result = input.All(Char.IsLetter);

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

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

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

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