2016-04-06 101 views

回答

1

這取決於你正在嘗試做什麼。對於更復雜的情況,你可以/應該使用像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解決方案是減緩/重量級,你也可以自己分析它。

+0

非常感謝您的幫助! – nilcit