【问题标题】:Regex and While Loop - still shows false when true正则表达式和 While 循环 - 为真时仍显示为假
【发布时间】:2019-12-02 12:13:32
【问题描述】:

我正在尝试创建一个 while 循环以确保员工格式正确 - 但它仅在我第一次正确输入员工 ID 时才有效。

当我首先将错误的格式输入到 ID 中,然后再输入正确的格式时,它不会重新评估并将其识别为 true

这里是有问题的代码部分:

Console.Write("Please enter your employee ID:");
empID = Console.ReadLine();

string pattern = @"^\d{9}[A-Z]{1}$";

Match match = Regex.Match(empID, pattern);

while (match.Success != true)
{

    if (match.Success == true)
    {
        Console.WriteLine(empID);
    }
    else
    {
        Console.WriteLine("Incorrect employee ID - please try again");
        empID = Console.ReadLine();

    }
}

知道第二次正确输入时没有看到 empID 是什么原因吗?

谢谢

【问题讨论】:

  • empID 发生变化时,您是否期望match.Success 被重新评估?不会的。
  • 旁白:match.Success == true 的值应该非常接近match.Success。同样,while ( !match.Success ) 应该就足够了,除非您正在检查 true 的变化值。
  • 我在从网页复制输入时遇到正则表达式匹配问题,并且输入字符串包含“不可见”字符,如换行符 (\n) 和其他空白字符 (en.wikipedia.org/wiki/Whitespace_character)。如果是这种情况,您需要在正则表达式匹配之前修剪输入字符串 > stackoverflow.com/questions/6219454/…
  • 您好 - 感谢您的回复。 @BACON - 是的,我正在尝试重新评估错误,直到有人输入正确的值。但它忽略了有人最终输入了有效的 empID 的事实。当我尝试您建议的方法时,它告诉我我的“匹配”尚未定义,因此无法正常工作。 HABO-我正在尝试获取一个查看 empID 的循环,直到它是有效的。然后在代码中继续。我认为使用 Regex 可以做到这一点,但似乎不行?

标签: c#


【解决方案1】:

您不会在循环中更新匹配变量值。请在代码中查看我的cmets

// here you receive your employee id
Console.Write("Please enter your employee ID:"); empID = Console.ReadLine();

string pattern = @"^\d{9}[A-Z]{1}$";

// here you initialize your match variable by result of matching with regex
Match match = Regex.Match(empID, pattern);

while (match.Success != true)
{
    if (match.Success == true)
    {
        Console.WriteLine(empID);
    }
    else
    {
        Console.WriteLine("Incorrect employee ID - please try again");

        // here you read your new employee id, but match variable is not updated
        empID = Console.ReadLine();

        // this is what you missed
        match = Regex.Match(empID, pattern);
    }
}

【讨论】:

  • 或者,你知道的,切换到do..while 关注DRY 并避免写match = 两次
  • 谢谢你们!!! match = Regex.Match(empID, pattern);添加到 else 已经解决了我的循环问题!非常感谢!!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
  • 1970-01-01
  • 2017-07-25
  • 1970-01-01
  • 2016-12-14
  • 2011-09-28
  • 1970-01-01
相关资源
最近更新 更多