替换模板字符串中的变量
如 $amount$元$amountName$
根据输入参数 amount 1999 amountName 红包
输出 1999元红包
public static String replaceTemplateParams(String templateContent, Map<String, String> extMap) {
List<String> paramList = pickDynamicParamList(templateContent);
StringBuilder stringBuilder = new StringBuilder();
int startIndex = 0;
for (String param : paramList) {
String value = extMap.get(StringUtil.trim(param, '$'));
if (StringUtils.isBlank(value)) {
value = "";
}
int index = templateContent.indexOf(param, startIndex);
stringBuilder.append(templateContent, startIndex, index);
stringBuilder.append(value);
startIndex = index + param.length();
}
stringBuilder.append(templateContent.substring(startIndex));
return stringBuilder.toString();
}
private static List<String> pickDynamicParamList(String templateContent) {
List<String> result = Lists.newArrayList();
int startIndex = 0;
int endIndex = 0;
boolean enterDynamic = false;
char[] chars = templateContent.toCharArray();
for (int i = 0; i < chars.length; i++) {
if ('$' != chars[i]) {
continue;
}
if (!enterDynamic) {
startIndex = i;
enterDynamic = true;
} else {
endIndex = i;
enterDynamic = false;
}
if (!enterDynamic) {
String params = String.valueOf(Arrays.copyOfRange(chars, startIndex, endIndex + 1));
result.add(params);
}
}
return result;
}
public static String trim(String str, char c) {
char[] chars = str.toCharArray();
int len = chars.length;
int st = 0;
while ((st < len) && (chars[st] == c)) {
st++;
}
while ((st < len) && (chars[len - 1] == c)) {
len--;
}
return (st > 0) && (len < chars.length) ? str.substring(st, len) : str;
}
public static void main(String[] args) {
String templateContent = "$amount$元$amountName$";
Map<String, String> extMap = new HashMap<>();
extMap.put("amount", "1999");
extMap.put("amountName", "红包");
System.out.println(replaceTemplateParams(templateContent, extMap));
}