string对{}和map的替换符的一段代码(描述得不好,就是把map的值替换到{}里面)

import java.util.Map;
public class StringFormatUtil {

    private StringFormatUtil(){}


    public static String substitute(String tepl, Map<String, String> params) {
        String text = tepl;
        for(Map.Entry<String, String> entry:params.entrySet()){
            String key = entry.getKey();
            text = text.replaceAll("\\{" + key + "}", safeRegexReplacement(entry.getValue()));
        }
        return text;
    }

    private static String safeRegexReplacement(String replacement) {
        if (replacement == null) {
            return replacement;
        }

        return replacement.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\$", "\\\\\\$");
    }
}

 使用方法:

static String sqlTemplete = "insert into tree_node (TREE_NODE_ID, OBJECT_ID, TREE_NODE_NM, TREE_NODE_POSITION, TREE_NODE_TYPE_CODE, UPPER_TREE_NODE_ID) values('{nodeId}','0','{nodeNm}','0','8','{upperNodeId}');";

Map<String, String> params = new HashMap<String, String>();
        params.put("nodeId", String.valueOf(1));
        params.put("upperNodeId", String.valueOf(2));
        params.put("nodeNm", String.valueOf(3));
        System.out.println(StringFormatUtil.substitute(sqlTemplete, params));
 

 

你可能感兴趣的:(String)