Loading

使用正则表达式实现(加减乘除)计算器(C#实现)


起因:公司领导要求做一款基于行业规范的计算器,

然后需要用户输入一些数据,然后根据用户输入的数据满足某些条件后,再根据用户输入的条件二进行加减乘除运算。;-)

期间因为查找规范等形成数据表的某一列是带加减运算的,开发时又开动了一番脑筋(百度翻阅)才想出了解决办法。

最终是解决办法是根据用户输入的值W*4.26*10/100=X,其中(4.26*10/100)是保存在数据表中的某个值,取出这个值后把用户输入的数据形成一个新的计算式进行运算

string input=4000*4.26*10/100;  


public string compute(string input) {//各项正则表达式 string num = @"[\-]?([0-9]{1,}\.?[0-9]*)"; //匹配数字 string exp1 = @"(?<NUM1>" + num + ")" + @"(?<OP>[\*\/\^])" + @"(?<NUM2>" + num + ")"; //匹配乘法、除法、幂运算 string exp2 = @"(?<NUM1>" + num + ")" + @"(?<OP>[\+\-])" + @"(?<NUM2>" + num + ")"; //匹配加法、加法 //定义声明正则表达式 Regex isExp1 = new Regex(exp1); //乘法、除法、幂运算 Regex isExp2 = new Regex(exp2); //加法、减法 //创建匹配对象 Match mExp1, mExp2; //先处理表达式中的乘、除法、幂运算 mExp1 = isExp1.Match(input); while (mExp1.Success) { GroupCollection gc = mExp1.Groups; //组匹配 decimal num1 = Convert.ToDecimal(gc["NUM1"].Value); //取操作数NUM1 decimal num2 = Convert.ToDecimal(gc["NUM2"].Value); //取操作数NUM2 switch (gc["OP"].Value) //取运算符OP,并判断运算 { case "*": num1 *= num2; break; case "/": if (num2 == 0) //判断除数是否为0 { return "DivNumZero"; //返回除数为0标志字符串 } else { num1 /= num2; break; } } input = input.Replace(mExp1.Value, string.Format("{0:f2}", num1)); //把计算结果替换进表达式 mExp1 = isExp1.Match(input); //重新匹配乘法、除法 } //再处理加减法 mExp2 = isExp2.Match(input); while (mExp2.Success) { GroupCollection gc = mExp2.Groups; //组匹配 decimal num1 = Convert.ToDecimal(gc["NUM1"].Value); //取操作数NUM1 decimal num2 = Convert.ToDecimal(gc["NUM2"].Value); //取操作数NUM2 switch (gc["OP"].Value) //取运算符OP,并判断运算 { case "+": num1 += num2; break; case "-": num1 -= num2; break; } input = input.Replace(mExp2.Value, string.Format("{0:f2}", num1)); //把计算结果替换进表达式 mExp2 = isExp2.Match(input); //重新匹配加法、减法 } //把运算结果返回上一级 return input; }

 

posted @ 2019-10-14 14:44  Howe_______ღ  阅读(3174)  评论(0编辑  收藏  举报