public static void main(String[] args) {
String s="${name},你好!数智乐清门户的${module}栏目已超过${day}天未更新,请及时做好栏目信息更新工作。如已更新,请忽略本条信息。";
log.info("替换前:"+s);
Map<String,Object> params = new HashMap<>();
params.put("name","王海");
params.put("module","模块名称");
params.put("day","5");
//使用的时候建议定义为常量或者字段
Pattern p = Pattern.compile("(\\$\\{)([\\w]+)(\\})");
Matcher m = p.matcher(s);
StringBuffer sr = new StringBuffer();
while (m.find()) {
String group = m.group().replace("$", "").replace("{", "").replace("}", "");
if (params.get(group) == null) {
continue;
}
m.appendReplacement(sr, (String) params.get(group));
}
m.appendTail(sr);
Matcher m1 = p.matcher(sr.toString());
//可以判断出是否替换成功
if(!m1.find()){
log.info("替换后:"+sr.toString());
}
}
2、 %s占位符
String applyContent = "我叫%s,今年%s岁";
String content = String.format(applyContent, "王杰", "25");
System.out.println(content);
String name = "mysql_表名_ddd_2";
System.out.println(String.format("测试%S", name));
转 换 符 | 说 明 |
%s | 字符串类型 |
%c | 字符类型 |
%b | 布尔类型 |
%d | 整数类型(十进制) |
%x | 整数类型(十六进制) |
%f | 浮点类型 |
%o | 整数类型(八进制) |
%a | 十六进制浮点类型 |
%e | 指数类型 |
%g | 通用浮点类型(f和e类型中较短的) |
%h | 散列码 |
%% | 百分比类型 |
%tx | 日期与时间类型(x代表不同的日期与时间转换符 |
%n | 换行符 |