字符串替换工具类

public class Tools {

    private static Pattern pattern;

    static {
        pattern = Pattern.compile("((?<=\\{)([a-zA-Z_]{1,})(?=\\}))");
    }
    /**
     * 字符串替换, 将 {} 中的内容, 用给定的参数进行替换
     *
     * @param text
     * @param params
     * @return
     */
    public static String format(String text, Map params) {
        // 把文本中的所有需要替换的变量捞出来, 丢进keys
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            String key = matcher.group();
            text = StringUtils.replace(text, "{" + key + "}", params.get(key) + "");
        }
        return text;
    }

    public static String replace(String text, Object ... args) {
        return MessageFormat.format(text, args);
    }

    public static String replaceFormat(String text, Map map) {
        List keys = new ArrayList<>();

        // 把文本中的所有需要替换的变量捞出来, 丢进keys
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            String key = matcher.group();
            if (!keys.contains(key)) {
                keys.add(key);
            }
        }

        // 开始替换, 将变量替换成数字,  并从map中将对应的值丢入 params 数组
        Object[] params = new Object[keys.size()];
        for (int i = 0; i < keys.size(); i++) {
            text = text.replaceAll(keys.get(i), i + "");
            params[i] = map.get(keys.get(i));
        }


        return replace(text, params);
    }

    //测试
    public static void main(String[] args) {

        String text = "hello {user}, welcome to {place}! now timestamp is: {time} !";
        Map map = new HashMap<>(2);
        map.put("time", System.currentTimeMillis());
        map.put("place", "China");
        map.put("user", "Lucy");
        String res = replaceFormat(text, map);
        System.out.println(res); // 输出 : hello Lucy, welcome to China! now 2stamp is: 1,490,619,291,742 !
    }
}

你可能感兴趣的:(java)