2016-04-06 12 views

答えて

1

これは実行しようとしている内容によって異なります。より複雑なケースでは、ANTLRのようなパーサジェネレータを使用することができます。式があなたの例(単純な算術)よりも複雑でない場合は、JavaScript/Nashornを使って式を分析することができます。

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のソリューションは、/ヘビー級を遅くすることであるならば、あなたもそれを自分で解析することができます:あなたができるUse the backreference in a regex to replace a text dynamicallyのソリューションを使用して

+0

ご協力いただきありがとうございます。 – nilcit

関連する問題