短信模板占位符替换
使用java.util.regex.Matcher类中的group根据正则找出模板占位符后,进行替换,再以此将文本拼接起来。
package com.iflytek.service.modular.auth.common.utils;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author xyding6
* @Classname SmsAssembleUtil
* @Description TODO
* @date 2024/12/9
*/
public class SmsAssembleUtil {
/**
* 根据模块及类型获取短信模板并组装报文
* @return
*/
public static String assembleSmsContent(Map<String,String> smsModel, String msgTemplateContent) throws Exception {
if (smsModel == null || StringUtils.isBlank(msgTemplateContent)) {
throw new RuntimeException("找不到短信模板");
}
//获取短信模板内容
//替换短信内容的自定义字段
Pattern p = Pattern.compile("[{]([\\w]+)[}]");
Matcher m = p.matcher(msgTemplateContent);
StringBuffer buf = new StringBuffer();
while (m.find()){
m.appendReplacement(buf, StringUtils.isNotBlank(smsModel.get(m.group(1))) ? smsModel.get(m.group(1)) : "");
}
m.appendTail(buf);
return buf.toString();
}
public static void main(String[] args) throws Exception {
String msgTemplateContent = "尊敬的{user_name}用户,您正在进行手机号码登录操作。验证码为:{msg_code}。如非本人操作,还请忽略。五分钟内有效。";
Map<String,String> smsModel = new HashMap<>();
smsModel.put("user_name","艾丁");
smsModel.put("msg_code","4399");
String msgContent = SmsAssembleUtil.assembleSmsContent(smsModel, msgTemplateContent);
System.out.println("msgContent = " + msgContent);
}
}