Search code examples
javamathematical-expressions

Check if a string is a mathematical expression or not?


I am trying to write a method in Java that accepts a string as an argument. Now this string may be a mathematical expression or it may be just an ordinary string. I have to evaluate it only if it is a mathematical expression and leave it alone if it isn't. I'll evaluate the mathematical expression using java script engine as follows:

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String foo = "1+2*10";
System.out.println(engine.eval(foo));

But the problem is if I pass a string that is not a mathematical expression, this throws an exception. I don't want exceptions in my code. What I am trying to achieve is something like this:

if(isExpression(foo))
{
engine.eval(foo);
}

This way I check whether it is a mathematical expression or not before evaluating it. Is there an easy implementation of the method isExpression(foo)? May be using some regular expression? Please let me know if there is any. Thanks


Solution

  • For really complex operations like this, the effort to see if it is a valid formula is almost as much as the effort to actually do the evaluation.

    I recommend that you just try to evaluate and, on a failure, throw a domain specific exception, say a CannotEvaluateFormulaException, and catch it.