Data-Processer
Data-Processer copied to clipboard
特殊场景会抛异常
TemplateAnalyseUtils类。第43行。 tpl如下 $Func{intRand()}|$Var{tmp}=$Func{doubleRand(0,10,2)}|"$Dic{ot}"|"$Var{tmp}"|"$Dic{b}" 此处判断hasfun是true,hasvar是true,但其实hasvar是后面的。此时funcIndex值是0,执行到这一行的时候数组越界。 template.charAt(funcIndex-1) == eq && template.charAt(funcIndex-2) == closeBrace
TemplateAnalyseUtils类添加了两个变量,并修改了analyse和extractVar两个函数。未做其他改动,且测试通过。希望可以覆盖提交,多谢。
private static final String VAR_GET = "\\$Var\\{\\s*.+\\s*\\}";
private static final String VAR_REGEX = "\\$Var\\{\\s*.+\\s*\\}\\s*=\\s*$";
private static void analyse(String template, int itemIndex,
Map<String, String> tplVar) {
int fstFunc = template.indexOf(PRE_FUNC);
int fstDic = template.indexOf(PRE_DIC);
if (fstFunc >= 0 && (fstDic > fstFunc || fstDic < 0)) { // 如果有函数,同时是最靠前的,先解析函数
// func
int funcEndIndex = template.indexOf("}", fstFunc);
String func = template.substring(fstFunc, funcEndIndex + 1);
String funcKey = "F" + StringUtils.formatNumber("" + itemIndex, 3) + "-"
+ func;
tplVar.put(funcKey, func);
// 解析var var需要与func联合使用
Pattern pattern = Pattern.compile(VAR_REGEX);
Matcher matcher = pattern.matcher(template.substring(0, fstFunc));
while (matcher.find()) {
Pattern p = Pattern.compile(VAR_GET);
Matcher m = p.matcher(matcher.group());
while (m.find()) {
String varName = m.group();
String varKey = "V" + StringUtils.formatNumber("" + itemIndex, 3)
+ "-" + varName;
// System.out.println("Func: " + varKey + "===>" + funcKey);
tplVar.put(varKey, funcKey);
}
}
analyse(template.substring(funcEndIndex + 1), ++itemIndex, tplVar);
}
if (fstDic >= 0 && (fstDic < fstFunc || fstFunc < 0)) { // dic
int dicEndIndex = template.indexOf("}", fstDic);
String dic = template.substring(fstDic, dicEndIndex + 1);
String dicKey = "D" + StringUtils.formatNumber("" + itemIndex, 3) + "-"
+ dic;
tplVar.put(dicKey, dic);
// 解析var var需要与func联合使用
Pattern pattern = Pattern.compile(VAR_REGEX);
Matcher matcher = pattern.matcher(template.substring(0, fstDic));
while (matcher.find()) {
Pattern p = Pattern.compile(VAR_GET);
Matcher m = p.matcher(matcher.group());
while (m.find()) {
String varName = matcher.group();
String varKey = "V" + StringUtils.formatNumber("" + itemIndex, 3)
+ "-" + varName;
// System.out.println("Func: " + varKey + "===>" + funcKey);
tplVar.put(varKey, dicKey);
}
}
analyse(template.substring(dicEndIndex + 1), ++itemIndex, tplVar);
}
}
/**
* 抽取模版中的函数,词典,自定义变量等
*
* @param template
* @return
*/
public static Map<String, String> extractVar(String template) {
Map<String, String> tplVar = new TreeMap<String, String>();
analyse(template, 0, tplVar);
return tplVar;
}