Java 用另一个子字符串(值)问题替换子字符串(模式)

Java Replace sub-string (pattern) by another sub-string (value) issue

我有一个小 api 通过更新 属性 持有者(模式 {{property_name}}

将一个字符串转换为另一个字符串

这是我的尝试:

public class TestApp {

    public static void main(String[] args) {
        Map<String, String> props = new HashMap<>();
        props.put("title", "login");

        String sourceTitle = "<title>{{ title }}</title>";
        System.out.println(updatePropertyValue(sourceTitle, props));

        // Print: <title>login</title>

        // ERROR if
        props.put("title", "${{__messages.loginTitle}}");
        System.out.println(updatePropertyValue(sourceTitle, props));
        // Expected: <title>${{__messages.loginTitle}}</title>

        // Exception:

        // Exception in thread "main" 
        // java.lang.IllegalArgumentException: named capturing group has 0 length name
        // at java.util.regex.Matcher.appendReplacement(Matcher.java:838)
    }

    static String updatePropertyValue(String line, Map<String, String> properties) {
        for (Entry<String, String> entry : properties.entrySet()) {
            String holder = "\{\{\s*" + entry.getKey() + "\s*\}\}";
            line = Pattern.compile(holder, Pattern.CASE_INSENSITIVE)
                          .matcher(line).replaceAll(entry.getValue());
        }
        return line;
    }
}

如果 属性 值没有任何特殊字符,如 $.

,它工作正常

请假设 属性 键仅包含字母。

有什么解决办法吗?谢谢!

我猜你需要正则表达式转义 entry.getKey() 部分。 This 应该有助于做到这一点。

使用Pattern.quoteReplacement转义替换中的所有元字符。