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

238 views Asked by At

I have a small api to convert a string to another string by updating property holders (pattern {{property_name}}

Here is my try:

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

It works fine If the property value does not have any special characters such as $.

Please assume that property keys include letters only.

Any solution? Thanks!

2

There are 2 answers

0
Andy Turner On BEST ANSWER

Use Pattern.quoteReplacement to escape all metacharacters in the replacement.

2
Abhishek Bhatia On

I guess you need to regex escape entry.getKey() part. This should help in doing that.