【问题标题】:Validating ID Number C#验证 ID 号 C#
【发布时间】:2021-12-05 19:48:05
【问题描述】:

我正在研究这种验证学生 ID 号的方法。身份证号码的凭证是;第一个字符必须是 9,第二个字符必须是 0,不能有任何字母,并且数字必须是 9 个字符长。如果学生 ID 有效,该方法将返回 true。当我通过 main 手动测试该方法时,即使我输入了错误的输入,结果也是如此。在我的代码中,我嵌套了 if 语句,但我最初并没有嵌套它们。有什么更好的方法来验证输入以与 ID 号的凭据保持一致?将字符串转换成数组会更理想吗?

 public static bool ValidateStudentId(string stdntId)
        {
            string compare = "123456789";
            if (stdntId.StartsWith("8"))
            {
                if (stdntId.StartsWith("91"))
                {
                    if (Regex.IsMatch(stdntId, @"^[a-zA-Z]+$"))
                    {
                        if (stdntId.Length > compare.Length)
                        {
                            if (stdntId.Length < compare.Length)
                            {
                                return false;
                            }
                        }
                    }
                }
            }

【问题讨论】:

  • 当您测试“不是字母”时,您会忽略(接受)符号。在这种情况下最好检查“仅数字”

标签: c# string validation if-statement boolean-expression


【解决方案1】:

你可以试试正则表达式

public static bool ValidateStudentId(string stdntId) => stdntId != null &&
  Regex.IsMatch(stdntId, "^90[0-9]{7}$");

模式解释:

  ^        - anchor - string start 
  90       - digits 9 and 0
  [0-9]{7} - exactly 7 digits (each in [0..9] range) 
  $        - anchor - string end

所以我们总共有9 个数字(90 前缀 - 2 个数字 + 7 个任意数字),从 90 开始

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多