Skip to main content
 首页 » 编程设计

c#之正则表达式和 While 循环之为真时仍显示假

2024年01月21日29grandyang

我正在尝试制作一个 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 视为正确的原因吗?

谢谢

请您参考如下方法:

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

// 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); 
    } 
}