问题描述
伙计们,我正在研究一个评估字符串数学表达式的系统.
Guys I am working on a system that evaluates string mathematical expression.
我的班级进行计算
public Double Calculate(string argExpression)
{
//get the user passed string
string ExpressionToEvaluate = argExpression;
//pass string in the evaluation object declaration.
Expression z = new Expression(ExpressionToEvaluate);
//command to evaluate the value of the **************string expression
var result = z.Evaluate();
Double results = Convert.ToDouble(result.ToString());
return results;
}
还有我的电话代码.
Double Finalstat = calculator.Calculate(UserQuery);
直到现在我的表情都是
4 + 5 + 69 * (100*3)
但是,在测试过程中,我发现表达式也可能会失真(因为它是用户构建的).像
However during testing I found that the expression may also be distorted(as it is user built).To things like
45+99abs - 778anv
所以我想知道是否有一种方法可以在将用户构建的(表达式)发送给班级中的用户进行评估之前?
So I wanted to know if there is a way of validating the user-built(expression) before sending it to be evaluated in the class ?
推荐答案
使用正则表达式,由于必须验证括号这一简单事实,您将遇到问题:
With regexes you will have a problem due to simple fact you have to validate parentheses:
abs(sin(log(...)))
您应该解析表达式,而不仅仅是将其与某种模式匹配.编写解析器规则也更加简洁和易于理解.作为奖励,您不仅可以进行验证,还可以对表达式进行评估.我的套件 NLT 包含了C#所需的一切(已经包含了简单的计算器),并且说您会喜欢通过添加abs
来增强它.
You should parse the expression, not just match it against some pattern. Writing parser rules is also much cleaner and easier to understand. As a bonus you will get not only validation but also evaluation of the expression. My suite NLT contains everything you need for C# (there is already simple calculator included), and say you would like to enhance it by adding abs
.
您可以省略词法分析器部分,然后直接进入解析器:
You can omit lexer section, and go right to parser:
expr -> "abs" "(" e:expr ")" // pattern
{ Math.Abs(e) }; // action
假设expr
已通过求和,减法等定义.
assuming expr
is already defined with sum, subtraction, and so on.
对于好奇的灵魂-不是"abs("
,因为在abs ( 5 )
这样的情况下会给出错误(无效的表达式).
For curious soul -- not "abs("
because in such case as abs ( 5 )
would give error (invalid expression).
这篇关于验证字符串数学表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!