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; } }