简单动态变量文本模板

TemplateUtils工具类

import lombok.experimental.UtilityClass;
import org.springframework.cglib.beans.BeanMap;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * TemplateUtils
 *
 * @author kancy
 * @date 2022/8/27 19:43
 */
@UtilityClass
public class TemplateUtils {

    /**
     * 变量占位符匹配正则
     */
    private static final Pattern pattern = Pattern.compile("(\\$\\{(.*?)})");

    /**
     * 解析
     *
     * @param templateStr 模板str
     * @param bean        豆
     * @return {@link String}
     */
    public String parse(String templateStr, Object bean){
        if (!templateStr.contains("$")){
            return templateStr;
        }
        return parse(templateStr, BeanMap.create(bean));
    }

    /**
     * 解析
     *
     * @param templateStr 模板str
     * @param params      参数
     * @return {@link String}
     */
    public String parse(String templateStr, Map<String, Object> params){
        if (!templateStr.contains("$")){
            return templateStr;
        }

        String template = templateStr;
        Map<String, String> variableMap = getVariableMap(template);
        Set<Map.Entry<String, String>> entries = variableMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (params.containsKey(key)){
                template = template.replace(value, String.valueOf(params.get(key)));
            }
        }
        return template;
    }

    /**
     * 解析变量名
     *
     * @param templateStr 模板str
     * @return {@link List}<{@link String}>
     */
    public List<String> parseVariableNames(String templateStr){
        return new ArrayList<>(getVariableMap(templateStr).keySet());
    }

    /**
     * 获取变量映射
     *
     * @param templateStr 模板str
     * @return {@link Map}<{@link String}, {@link String}>
     */
    private Map<String, String> getVariableMap(String templateStr) {
        Matcher matcher = pattern.matcher(templateStr);
        Map<String, String> variableMap = new HashMap<>();
        while (matcher.find()) {
            variableMap.put(matcher.group(2).trim(), matcher.group(1));
        }
        return variableMap;
    }

}

posted @ 2022-08-27 22:30  kancy  阅读(50)  评论(0编辑  收藏  举报