如何检查用户名是否有 3 位数字

How to check if a username has 3 digits

我希望用户只有在用户名的最后 3 个字符是数字时才能继续。你会如何编码?如有任何帮助,我们将不胜感激!

我当前的代码不起作用:

static bool checkUsername(string user)
        {
            //bool containsAtLeastThreeDigits = user.Any(char.IsDigit);
            var counter = user.Count(x => Char.IsDigit(x));
            bool valid = false;
            int count = 0;

            if (counter == 3)
            {
                count++;
            }
            else
            {
                Console.WriteLine("Password must have 3 digits");
            }

            if (count == 1)
            {
                valid = true;
            }
            return valid;
        }

可以简单的检查Length是否大于2个字符,然后检查最后3个字符组成的子串是否都是数字:

public static bool Last3AreDigits(string input)
{
    return input?.Length > 2 && input.Substring(input.Length - 3).All(char.IsDigit);
}

编辑:我刚刚看到 Casey Crookston 关于您的问题含糊不清的评论。因此,如果您确实想检查输入是否在 any 位置至少有 3 位数字,您可以使用以下内容:

using System.Linq;

static bool checkUsername(string user)
{
    return user?.Count(char.IsDigit) >= 3;
}

原始答案(检查最后 3 个字符是否为数字)

您可以通过几种比您目前正在做的更简单的方式来完成此操作。

using System.Linq;

static bool checkUsername(string user)
{
    return user?.Length >= 3 && user.TakeLast(3).All(char.IsDigit);
}

using System.Text.RegularExpressions;

static bool checkUsername(string user)
{
    return user != null && Regex.Match(user, @"\d{3}$").Success;
}

\d表示一个数字,{3}表示前面的表达式出现3次(即3个数字),$表示匹配到字符串的末尾。

因为其他人都在使用 Linq and/or Regex,这里有一个使用 SubStringTryParseIndexOfAny 的解决方案:

//1. Checks for Length of at least 3 characters
//2. Tries parsing to a number
//3. Check to make sure a successful parse is a number and doesn't contain {, . + -}. 
//Don't want false positives of things like +10 or -99 etc.
public static bool CheckUsername(string user)
{
    return user?.Length >= 3 && 
           Int32.TryParse(user.Substring(user.Length - 3), out _) && 
           user.Substring(user.Length - 3).IndexOfAny(new char[] { ',', '+', '-', '.' }) == -1;
}

最简单的选择是验证长度是否大于某个最小值,然后使用新的 C# 范围索引。我确定您可能还想进行其他验证。但只是您陈述的要求看起来像这样:

    static readonly (string,bool)[] UsernamesTestData = new (string,bool)[]
        {
            ("good123",true),
            ("bad12",false),
            ("bad1",false),
            ("no",false),
            (" ",false),
            ("",false),
            (null,false),
        };

    static void Main(string[] _)
    {
        foreach (var (username, expected) in UsernamesTestData)
        {
            bool isValid = IsValidUsername(username);

            Console.WriteLine($"{username}: expected: {expected} tested as: {isValid}");
        }
    }

    static bool IsValidUsername(string name)
    {
        if (string.IsNullOrWhiteSpace(name) || name.Length < 4)
            return false;

        return char.IsDigit(name[^1]) && char.IsDigit(name[^2]) && char.IsDigit(name[^3]);
    }

还有 old-school 方法可以做到这一点:检查长度,然后使用循环检查最后三个字符:

public static bool Last3AreDigits(string name)
{
    if (name == null || name.Length < 3) return false;

    for (int i = name.Length - 1; i > name.Length - 4; i--)
    {
        if (!char.IsDigit(name[i])) return false;
    }

    return true;
}