string対{}とmapの置換子のコード(説明が悪いのは、mapの値を{}に置換することです)

1571 ワード

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));