Visual Studio在我的新Regex var中捕获了一个错误
本文关键字:错误 一个 我的 Studio Regex var Visual | 更新日期: 2023-09-27 17:55:32
由于某种原因,Visual Studio在var regexItem创建行上捕获了一个错误。
我"} 意料之中。"
以为我错过了一个结束的"}",但我认为这与创建正则表达式变量有关(我第一次尝试使用正则表达式)。
对于上下文:我想确保用户只在"问题"字符串中键入 0-9、逗号、小数、运算 (+/*-) 或等号。
感谢您的任何和所有帮助。这是代码块:
private static bool MainMenu()
{
Console.WriteLine("Enter an equation to solve (use +, -, *, or /) or 'exit' to quit.");
string problem = Console.ReadLine();
if (problem.Equals("exit", StringComparison.OrdinalIgnoreCase))
{
return false;
}
var regexItem = new Regex("^[0-9/*+,.-=]+$");
else if (regexItem.IsMatch(problem))
{
Calculate(problem);
return true;
}
else
{
Console.WriteLine("Your entry is invalid. Please only enter numbers and operations. :)");
return true;
}
}
更改
else if (regexItem.IsMatch(problem))
自
if (regexItem.IsMatch(problem))
当前解决方案有两个问题:
else if (regexItem.IsMatch(problem))
行上的"野生"else
,应将其删除以便编译代码- 正则表达式包含未转义连字符在字符类中创建范围的已知问题。 使用
"^[0-9/*+,.=-]+$"
,其中连字符放在字符类的末尾,不必转义。或者@"^[0-9/*+,.'-=]+$"
(没有人能够破坏模式,因为添加更多符号不应该破坏模式)。