Java regular expression how to add 2 values?

How can I parse and add two values? I am using this template:

String s = "6 + 7 ="; 

Interval on, I need to get "13"

Is it possible with regex, or is there another way to do this easily?

Thanks in advance for helping ur.

0
source share
2 answers

If you want to use regex, you can do it like this:

 Pattern pattern = Pattern.compile("(\\d+)\\s*\\+\\s*(\\d+)\\s*="); Matcher matcher = pattern.matcher("6 + 7 ="); if (matcher.matches()) { System.out.println(Integer.valueOf(matcher.group(1)) + Integer.valueOf(matcher.group(2))); } 
+2
source

Is this a regular expression needed? If not, you can use the JavaScript engine (starting with Java 1.6) to perform calculations from String, for example:

 ScriptEngineManager factory = new ScriptEngineManager(); // create a JavaScript engine ScriptEngine engine = factory.getEngineByName("JavaScript"); Double d=(Double)engine.eval("1 + 2 * 3"); System.out.println(d); 
+1
source

All Articles