0

how can I parse and addition two value? Im usin this pattern:

String s = "6 + 7 =";

Included spacing, I need to get "13"

It is possible with regex, or there are an other way to do this easely?

Thanks in advance for ur help.

0

2 Answers 2

2

If you want to use regex you can do it this way:

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)));
}
Sign up to request clarification or add additional context in comments.

Comments

1

Does it have to be regex? If not you can use JavaScript engine (since Java 1.6) to do calculations from String, like:

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.