首页 > 其他分享 >自定义占位符替换工具类

自定义占位符替换工具类

时间:2023-05-26 21:55:36浏览次数:36  
标签:String 自定义 public 占位 source import 替换 name

添加依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

工具类

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PlaceholderUtils {

    /**
     * 占位符正则表达式:$+花括号
     * <p>占位符示例:{@code ${xxx}}</p>
     */
    public static final Pattern PATTERN_BRACE = Pattern.compile("\\$\\{(.*?)}");

    /**
     * 占位符正则表达式:$+尖括号
     * <p>占位符示例:{@code $<xxx>}</p>
     */
    public static final Pattern PATTERN_ANGLE = Pattern.compile("\\$<(.*?)>");

    /**
     * 匹配器
     */
    private static Matcher matcher;

    /**
     * 替换字符串占位符,可变参数,字符串中使用{0}{1}...{*}顺序下标,表示占位符
     *
     * @param source 需要匹配的字符串,示例:"名字:{0},年龄:{1},学校:{2}"
     * @param params 可变参数,动态参数
     * @return 替换后的字符串
     */
    public static String replaceWithVarargs(String source, Object... params) {
        return MessageFormat.format(source, params);
    }

    /**
     * 替换字符串占位符,Map传参,字符串中使用${key}表示占位符
     *
     * @param source 需要匹配的字符串,示例:"名字:${name},年龄:${age},学校:${school}"
     * @param params 参数集,Map类型
     * @return 替换后的字符串
     */
    public static String replaceWithMap(String source, Map<String, Object> params) {
        if (StringUtils.isBlank(source) || CollectionUtils.isEmpty(params)) {
            return source;
        }
        String targetString = source;
        matcher = PATTERN_BRACE.matcher(source);
        while (matcher.find()) {
            try {
                String key = matcher.group();
                //如果占位符是{} 这里就是key.substring(1, key.length() - 1).trim()
                String keyClone = key.substring(2, key.length() - 1).trim();
                Object value = params.get(keyClone);
                if (value != null) {
                    targetString = targetString.replace(key, value.toString());
                }
            } catch (Exception e) {
                throw new RuntimeException("字符串格式化程序失败", e);
            }
        }
        return targetString;
    }

    /**
     * 替换字符串占位符,POJO传参,字符串中使用${key}表示占位符
     *
     * <p>注:利用反射,自动获取对象属性值 (必须有get方法) </p>
     *
     * @param source 需要匹配的字符串
     * @param params 参数实体
     * @return 替换后的字符串
     */
    public static String replaceWithObject(String source, Object params) {
        if (StringUtils.isBlank(source) || ObjectUtils.isEmpty(params)) {
            return source;
        }

        String targetString = source;

        PropertyDescriptor pd;
        Method getMethod;

        // 匹配${}中间的内容 包括括号
        matcher = PATTERN_BRACE.matcher(source);
        while (matcher.find()) {
            String key = matcher.group();
            String holderName = key.substring(2, key.length() - 1).trim();
            try {
                pd = new PropertyDescriptor(holderName, params.getClass());
                // 获得get方法
                getMethod = pd.getReadMethod();
                Object value = getMethod.invoke(params);
                if (value != null) {
                    targetString = targetString.replace(key, value.toString());
                }
            } catch (Exception e) {
                throw new RuntimeException("字符串格式化程序失败", e);
            }
        }
        return targetString;
    }

    /**
     * 获取String中的占位符keys
     * <p>示例:名字:${name},年龄:${age},学校:${school},返回:Set[name,age,school]</p>
     *
     * @param source  源字符串
     * @param pattern 正则表达式,pattern示例:<pre> {@code
     *                // 尖括号:<placeHolder> 表示为占位符
     *                Pattern pattern = Pattern.compile("\\$<(.*?)>");
     *
     *                // 大括号:{placeHolder} 表示为占位符, 上面的示例中就使用{}作为占位符
     *                Pattern pattern = Pattern.compile("\\$\\{(.*?)}");
     *                } </pre>
     * @return Set集合
     */
    public static Set<String> getPlaceholderKeys(String source, Pattern pattern) {
        Set<String> placeHolderSet = new HashSet<>();

        // 参数有误返回空集合
        if (StringUtils.isBlank(source) || ObjectUtils.isEmpty(pattern)) {
            return placeHolderSet;
        }

        // 根据正则表达式初始匹配器
        matcher = pattern.matcher(source);
        while (matcher.find()) {
            //示例: {name}
            String key = matcher.group();
            //示例: name
            String placeHolder = key.substring(2, key.length() - 1).trim();
            placeHolderSet.add(placeHolder);
        }

        return placeHolderSet;
    }
}

 

实体

package com.tangsm.domain;

/**
 * 用户信息
 *
 * @author tangsm
 */
public class UserInfo {
    /**
     * 姓名
     */
    private String name;

    /**
     * 年龄
     */
    private Integer age;

    /**
     * 学校
     */
    private String school;

    /**
     * 无参构造
     */
    public UserInfo() {
    }

    /**
     * 全参构造
     *
     * @param name   名称
     * @param age    年龄
     * @param school 学校
     */
    public UserInfo(String name, Integer age, String school) {
        this.name = name;
        this.age = age;
        this.school = school;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSchool() {
        return school;
    }

    public void setSchool(String school) {
        this.school = school;
    }
}

 

测试类

package com.tangsm.util;

import com.tangsm.domain.UserInfo;
import com.tangsm.util.PlaceholderUtils;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;

/**
 * 自定义占位符替换工具类测试类
 *
 * @author tangsm
 */
public class PlaceholderUtilsTest {
    private final Logger log = LoggerFactory.getLogger(PlaceholderUtilsTest.class);

    private static final String SOURCE0 = "名字:{0},年龄:{1},学校:{2}";
    private static final String SOURCE1 = "名字:${name},年龄:${age},学校:${school}";
    private static final String SOURCE2 = "名字:$<name>,年龄:$<age>,学校:$<school>";

    /**
     * 替换字符串占位符,动态参数,字符串中使用{0}{1}...{*}顺序下标,表示占位符,测试方法
     */
    @Test
    void replaceWithVarargs() {
        log.info("replaceWithVarargs,处理结果:{}", PlaceholderUtils.replaceWithVarargs(SOURCE0, "小美", 18, "女高一中"));
    }

    /**
     * 替换字符串占位符,Map传参,字符串中使用${key}表示占位符,测试方法
     */
    @Test
    void replaceWithMap() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("name", "小美");
        params.put("age", 18);
        params.put("school", "女高一中");
        log.info("replaceWithMap,处理结果:{}", PlaceholderUtils.replaceWithMap(SOURCE1, params));
    }

    /**
     * 替换字符串占位符,POJO传参,字符串中使用${key}表示占位符,测试方法
     */
    @Test
    void replaceWithObject() {
        UserInfo userInfo = new UserInfo("小美", 18, "女高一中");
        log.info("replaceWithObject,处理结果:{}", PlaceholderUtils.replaceWithObject(SOURCE1, userInfo));
    }

    /**
     * 获取String中的占位符keys
     */
    @Test
    void getPlaceholderKeys() {
        log.info("getPlaceholderKeys-PATTERN_BRACE,处理结果:{}", PlaceholderUtils.getPlaceholderKeys(SOURCE1, PlaceholderUtils.PATTERN_BRACE));
        log.info("getPlaceholderKeys-PATTERN_ANGLE,处理结果:{}", PlaceholderUtils.getPlaceholderKeys(SOURCE2, PlaceholderUtils.PATTERN_ANGLE));
    }
}

 

测试结果

PlaceholderUtilsTest - replaceWithObject,处理结果:名字:小美,年龄:18,学校:女高一中
PlaceholderUtilsTest - getPlaceholderKeys-PATTERN_BRACE,处理结果:[school, name, age]
PlaceholderUtilsTest - getPlaceholderKeys-PATTERN_ANGLE,处理结果:[school, name, age]
PlaceholderUtilsTest - replaceWithVarargs,处理结果:名字:小美,年龄:18,学校:女高一中
PlaceholderUtilsTest - replaceWithMap,处理结果:名字:小美,年龄:18,学校:女高一中
————————————————
版权声明:本文为CSDN博主「湯神码」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/tangyb828/article/details/128257386

 

标签:String,自定义,public,占位,source,import,替换,name
From: https://www.cnblogs.com/ixtao/p/17435905.html

相关文章

  • 前端自定义弹框组件、自定义弹框内容alertView popup组件
    快速实现前端自定义弹框、自定义弹框内容alertViewpopup组件,请访问uni-app插件市场地址:https://ext.dcloud.net.cn/plugin?id=12491 效果图如下:  代码如下:#自定义弹框使用方法####HTML代码部分```html<template><viewclass="content"><imageclass="logo"sr......
  • 异常的捕获和抛出、自定义异常类
    捕获异常捕获格式:try{/*可能出现异常的代码块*/}catch(异常类型变量e){异常出现后执行的语句}finally{不管是否出现异常都要执行的语句,通常用于IO流文件的关闭}catch语句可连续有多个,和ifelse语法一样,但是最大最广泛的exception需要放最后throw和throws抛出异常t......
  • 英文双引号替换成中文双引号
    1.字符串中的英文双引号变成中文双引号///<summary>///替换字符串中的英文双引号为中文双引号///</summary>///<paramname="str"></param>///<returns></returns>publicstaticstringReplaceYinHaoEnToCn(stringstr){stringnewStr="......
  • BooleanBuilder 如何根据自定义列名 模糊查询 使用PathBuilder
     //动态传参//1.声明PathBuilder:MyTable为类名称,"myTable"为首字母小写后的类名PathBuilder<MyTable>path=newPathBuilder<>(MyTable.class,"myTable");//2.判断查询的列的名称是否不为空if(!ObjectUtils.isEmpty(xXXXCondition.getColumn1())){ Stri......
  • Go 语言 - 自定义 log
    Go语言-自定义logCode/go/go_log_demovia......
  • .env.development(开发环境)、.env.prodction(正式环境)、自定义环境 例如:读取vue项目根
    .env.development(开发环境)、.env.prodction(正式环境)、自定义环境原文链接:https://blog.csdn.net/qq_42855675/article/details/114261585文章目录1.配置文件:2.命名规则3.关于文件的加载使用自定义环境1.配置文件:      .env.development:开发环境下的配置文件 ......
  • FLEX4实践—自定义控件皮肤
     设计需求: 1)对于界面上的TextInput控件,需要设置‘必填’与‘非必填’两种状态 2)对于‘必填’状态希望给与控件特殊的显示样式 3)希望能简化代码,不需要每次使用TextInput控件都要对其置样式  方案1:将样式控制写入css文件,通过Style属性控制TextInput的显示 方案2:利用Flex......
  • 合集 替换子关键词
    代码list_ZFI077=df_1.columns.tolist()df_ZFI077=df_1.columns.to_frame(name="列名")#先不重置索引drop依据索引df_ZFI077_1=df_ZFI077.copy().reset_index(drop=True)#index.to_frame()后需重置索引方便赋值fori,jinenumerate(list_ZFI077):ifdf_ZFI0......
  • Mybatis-Plus自动生成代码,自定义Controller
    MP网址:https://baomidou.com/pages/779a6e/#%E4%BD%BF%E7%94%A8直接copy官网代码修改成自己的:privatevoidgenerate(){FastAutoGenerator.create("jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2b8","root","P@ss123.")......
  • 如何在Angular应用程序中插入自定义 CSS?这里有答案!
    KendoUIforAngular是专用于Angular开发的专业级Angular组件,telerik致力于提供纯粹的高性能AngularUI组件,无需任何jQuery依赖关系。KendoUIR12023正式版下载Telerik_KendoUI产品技术交流群:726377843    欢迎一起进群讨论为什么需要在Angular应用程序中插入自定义C......