In Java, if I have a string like "(3+5)x + x^(6/2)"
, how could I replace all expressions in parentheses with their evaluations, to get the string "8x + x^3"
?
Asked
Active
Viewed 684 times
1 Answers
1
It depends on what you are trying to do. For more complex cases, you could/should use a parser generator like ANTLR. If the expressions are not more complex then your examples (simple arithmetics), you could just try to analyze the expressions with JavaScript/Nashorn.
Using the solution of Use the backreference in a regex to replace a text dynamically you could do:
public static void main(String[] args) throws ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
String x = "(3+5)x + x^(6/2)";
// can also be extended to expressions like 3+5*5 with
// Pattern.compile("\\(\\d+([+/*-]\\d+)+\\)")
Pattern simpleArithmeticExpr = Pattern.compile("\\(\\d+[+/]\\d+\\)");
Matcher matcher = simpleArithmeticExpr.matcher(x);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
String expr = matcher.group();
String evaluatedExpr = String.valueOf(engine.eval(expr));
matcher.appendReplacement(sb, evaluatedExpr );
}
matcher.appendTail(sb);
System.out.println(sb); // 8x + x^3
}
If the Javascript solution is to slow/heavyweight, you could also parse it yourself.

Community
- 1
- 1

user140547
- 7,750
- 3
- 28
- 80
-
thank you very much for your help! – nilcit Apr 06 '16 at 22:34