public static void main(String[] args) {
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("userName", "Jyang");
dataMap.put("password", "admin");
String template = "用户名称:${userName},用户密码:${password}";
/**
* 方式一:利用正则替换
*/
if (template.startsWith("$") || template.contains("$")) {
Pattern pattern = Pattern.compile("\\$\\{([^\\}]+)\\}");
Matcher matcher = pattern.matcher(template);
StringBuffer result = new StringBuffer();
// 根据正则替换
while (matcher.find()) {
String replacement = Objects.toString(dataMap.get(matcher.group(1)), "");
matcher.appendReplacement(result, replacement);
}
matcher.appendTail(result);
String newValue = Objects.toString(result);
System.out.println("替换后的值(方式一):" + newValue);
}
/**
* 方式二:借助org.apache.commons.lang3
*/
StrSubstitutor strSubstitutor = new StrSubstitutor(dataMap);
String newValue2 = strSubstitutor.replace(template);
System.out.println("替换后的值(方式二):" + newValue2);
}
Java替换${xxx}模板字符串
于 2024-09-21 16:42:17 首次发布