正则文本替换

举例:字符串 "{good}学学,{day}向上"  替换成   "好好学学,天天向上"

   /**
     * 字符串替换, 将 {} 中的内容, 用给定的参数进行替换
     * @param text 需要处理的文本
     * @param params 替换map
     * @return 替换后的文本
     */
    public static String format(String text, Map<String, Object> params) {
        String reg = "((?<=\\{)([a-zA-Z_]{1,})(?=\\}))";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            String key = matcher.group();
            text = text.replaceAll("\\{"+key+"\\}", params.get(key) + "");
        }
        return text;
    }
 
    public static void main(String[] args){
        Map<String,Object> map = new HashMap<>();
        map.put("good","好好");
        map.put("day","天天");
 
        String text = "{good}学习,{day}向上";
        String newText = format(text,map);
        System.out.println("newText: " + newText);
    }

猜你喜欢

转载自blog.csdn.net/iss_jin/article/details/121845246