代码
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTest {
public static void main(String[] args) {
Map<Integer, Double> map = new LinkedHashMap<>();
map.put(0,1.0);
map.put(1,1.0);
String formulas = "([q1] + [q2]) / 2 ";
double calculate = calculate(formulas, map);
System.out.println("calculate: " + calculate);
}
/**
*计算方法
*/
public double calculate(String formulas, Map<Integer, Double> questionScore) {
log.info("自定义分数计算,formulas={},questionScore={}", formulas, questionScore);
//即"\\[q\\d+]"。这个模式表示以"["开头,紧接着是字母"q",然后是一个或多个数字,最后以"]"结尾的字符串。
String regex = "\\[q\\d+]";
Pattern compile = Pattern.compile(regex);
//提取公式中的占位符 例:[q1]
Matcher m = compile.matcher(formulas);
//获取题号
List<Integer> qSeq = new ArrayList<>();
while (m.find()) {
//提取标志位中的题号
qSeq.add(Integer.valueOf(formulas.substring(m.start() + 2, m.end() - 1)));
}
String evalStr = null;
for (int i = 0; i < qSeq.size(); i++) {
Integer index = qSeq.get(i);
if (i == 0) {
//将题号 [q1]替换为对应的实际分数
evalStr = formulas.replace("[q" + index + "]", String.valueOf(questionScore.get(index)));
} else {
evalStr = evalStr.replace("[q" + index + "]", String.valueOf(questionScore.get(index)));
}
}
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object result = 0;
try {
if (Objects.isNull(evalStr)) {
throw new BizException("自定义公式不正确");
}
result = engine.eval(evalStr);
} catch (ScriptException e) {
log.info("转换分数异常");
}
BigDecimal two = BigDecimal.valueOf((Double) result);
return two.setScale(2, RoundingMode.HALF_UP).doubleValue();
}
结果
文章评论