java用另一个子字符串(值)替换子字符串(模式)

baubqpgj  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(437)

我有一个小api,可以通过更新属性持有者(模式{property\u 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;
    }
}

如果属性值没有任何特殊字符(如$),则可以正常工作。
请假设属性键只包含字母。
有什么解决办法吗?谢谢!

cxfofazt

cxfofazt1#

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

nkcskrwz

nkcskrwz2#

我想你需要正则表达式逃逸 entry.getKey() 部分。这样做应该会有帮助。

相关问题