-2

I have a string something like : String str="(2+(3*4))+(1+2)"; Somehow I want calculate its value in Integer format. i.e. I should be able to get 2+12+3=17. What matters for me is the End Result.

I used : str.replaceAll("\((.*?)\)", "$1"), which doesn't work properly and even I am not able to get the answer as Integer.

Can anyone Help me? Thanks in advance :)

devnull
  • 118,548
  • 33
  • 236
  • 227
Arshad
  • 19
  • 1
  • 8
    regex is not for calculation, it's for pattern matching. – John Woo Sep 20 '13 at 12:12
  • 2
    [In computing, a **regular expression** (abbreviated **regex** or **regexp**) is a sequence of characters that forms a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. "find and replace"-like operations.](http://en.wikipedia.org/wiki/Regular_expression) – devnull Sep 20 '13 at 12:16
  • 2
    This question appears to be off-topic because it is about using regular expressions to perform mathematical tasks. – devnull Sep 20 '13 at 12:17
  • 1
    possible duplicate of [Evaluating a math expression given in string form](http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form) – Joe Elleson Sep 20 '13 at 12:39

4 Answers4

4

Shunting-yard algorithm is good for that. Here's a java applet with sourcecode using this algorithm.

For expression evaluations, you can see these libraries-

Janino - This one is really amazing!

Jep Java

Mvel

Using builtin Javascript engine:

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class ExpressionEvaluation {

    public static void main(String... args) {

        final ScriptEngineManager mgr = new ScriptEngineManager();
        final ScriptEngine engine = mgr.getEngineByName("JavaScript");

        String expr = "(2+(3*4))+(1+2)";

        try {
            System.out.println(engine.eval(expr)); // prints out 17
        } catch(Exception ex){
            //TODO:  handle the exception
            ex.printStackTrace();
        }

    }
}
Sajal Dutta
  • 18,272
  • 11
  • 52
  • 74
3

Maybe you can use the ScripEngine class in Java and invoke the eval() function to evaluate the expression.

I think this link can help you.

++

Community
  • 1
  • 1
Jordan Montel
  • 8,227
  • 2
  • 35
  • 40
0

Check out Jeval

And this question

Community
  • 1
  • 1
Aydin
  • 311
  • 4
  • 15
0

Regex is not a good idea for that. You should parse the string and use a stack.

See here for the explanation of the algorithm (the third one): http://www.smccd.net/accounts/hasson/C++2Notes/ArithmeticParsing.html

Beleg
  • 140
  • 1
  • 9