-2
在Java中,如果我有像"(3+5)x + x^(6/2)"
这样的字符串,我怎样才能用括号替换括号中的所有表达式以得到字符串"8x + x^3"
?在括号中评估表达式,在字符串中
在Java中,如果我有像"(3+5)x + x^(6/2)"
这样的字符串,我怎样才能用括号替换括号中的所有表达式以得到字符串"8x + x^3"
?在括号中评估表达式,在字符串中
这取决于你正在尝试做什么。对于更复杂的情况,你可以/应该使用像ANTLR这样的解析器生成器。如果表达式不像你的例子那么复杂(简单的算术),你可以试着用JavaScript/Nashorn来分析表达式。
使用的Use the backreference in a regex to replace a text dynamically的解决方案,你可以这样做:
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
}
如果JavaScript解决方案是减缓/重量级,你也可以自己分析它。
非常感谢您的帮助! – nilcit