TemplateFormatUtils.java
1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.canrd.webmagic.common.utils;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* 消息模板占位符替换工具
*
* @author fanzhenyu
* @date 2022-04-20
*/
public class TemplateFormatUtils {
/**
* 正则 匹配 { + "多个任意字符" + }
*/
private static final String DEFAULT_REG = "\\{[\\w]+\\}";
/**
*
* @param text 原模板 占位符格式必须为:{fieldName}
* @param map 模板参数
* @return
*/
public static String replaceTemplateContent(String text, Map<String, String> map){
return replaceTemplateContent(text,map,DEFAULT_REG);
}
/**
*
* @param text 原模板 占位符格式必须为:{fieldName}
* @param map 模板参数
* @param reg 自定义占位符样式 - 正则匹配
* @return
*/
public static String replaceTemplateContent(String text,Map<String,String> map,String reg){
if(StringUtils.isBlank(reg)){
reg = DEFAULT_REG;
}
Pattern pattern = Pattern.compile(reg);
Matcher m = pattern.matcher(text);
while(m.find()){
String currentGroup = m.group();
String currentPattern = currentGroup.replaceAll("^\\{", "").replaceAll("\\}$", "").trim();
String mapValue = map.get(currentPattern);
if (mapValue != null){
text = text.replace(currentGroup, mapValue);
}
}
return text;
}
}