鉴于我的字符串如下:"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);
答案 0 :(得分:3)
将两个变量june1
和august1
绑定到脚本上下文中,而不用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(" + ", "");