Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Visual Studio正在捕获我的新正则表达式变量的错误_C#_Regex - Fatal编程技术网

C# Visual Studio正在捕获我的新正则表达式变量的错误

C# Visual Studio正在捕获我的新正则表达式变量的错误,c#,regex,C#,Regex,由于某种原因,Visual Studio在var regexItem创建行上捕获到错误 “}预期。” 我想我错过了一个结束“}”,但我认为这与Regex变量的创建有关(我第一次尝试使用Regex) 对于上下文:我想确保用户只在“问题”字符串中键入0-9、逗号、小数、运算(+/*-)或相等的符号 谢谢你的帮助。以下是代码块: private static bool MainMenu() { Console.WriteLine("Enter an equation t

由于某种原因,Visual Studio在var regexItem创建行上捕获到错误

“}预期。”

我想我错过了一个结束“}”,但我认为这与Regex变量的创建有关(我第一次尝试使用Regex)

对于上下文:我想确保用户只在“问题”字符串中键入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))
    行上的“wild”
    else
    ,为了编译代码,应该删除该行
  • 正则表达式包含一个已知的问题,即未开槽的连字符在字符类中创建了一个范围。使用
    “^[0-9/*+,.=-]+$”
    ,其中连字符放在字符类的末尾,不必转义。或者
    @“^[0-9/*+,.\-=]+$”
    (没有人能够破坏模式,因为添加更多符号不会破坏模式)

如果在<代码>的中间声明一个新的变量SMAK,如果……否则…你不能这么做。通过“捕获错误”,你的意思是它不会编译,对吗?正则表达式是错误的,
-=
创建了一个范围。避开连字符或放在字符类的末尾。谢谢你,保罗。这就是引发错误的原因。删除
else
不会解决正则表达式模式的问题。使用
“^[0-9/*+,.=-]+$”
else if (regexItem.IsMatch(problem))
if (regexItem.IsMatch(problem))