在Java中评估字符串表达式

时间:2018-07-25 23:41:13

标签: java string scriptengine

鉴于我的字符串如下:"june1 + august1"

我需要最终值才能评估为"julyseptember"

但是最终值当前为"july + september"

需要做些什么才能使字符串求值成我所需要的?

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
value = "june1 + august1";
value = value.replaceAll("june1", "july");
value = value.replaceAll("august1", "september");
script = "print(msg)";
engine.put("msg", value);
engine.eval(script);

2 个答案:

答案 0 :(得分:3)

将两个变量june1august1绑定到脚本上下文中,而不用replaceAll注入它们:

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");

String script = "june1 + august1";

engine.put("june1", "july");
engine.put("august1", "september");

String result = (String) engine.eval(script);

System.out.println(result);  // will output julyseptember

答案 1 :(得分:-2)

value = value.replaceAll(" + ", "");