-1

I have the following code:

    public String replaceValues(String string, HashMap hashMap){
    TestHashMap h = new TestHashMap();
    String str = new String(h.xmlToString());
    Iterator iterator = hashMap.entrySet().iterator();
    while(iterator.hasNext()){
        HashMap.Entry pair = (HashMap.Entry)iterator.next();
        str = str.replaceAll(pair.getKey().toString(), pair.getValue().toString());
    }
    return str; 
}

public static void main(String[] args) {
    TestHashMap h = new TestHashMap();
    HashMap<String, String> hmap = new HashMap<String, String>();
    hmap.put("{username}", "Tudor");
    hmap.put("{password}", "Tester123");
    System.out.println(hmap);
    String replace = h.replaceValues(h.xmlToString(), hmap);
    System.out.println(replace);
}

XML file looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<hashmap>
    <request>
        <username>{username}</username>
        <password>{password}</password>
    </request>
</hashmap>

This throws exception: Illegal repetition. But there is no way that i know of to escape the "{}" characters, because the way i'm getting those is with getKey() and getValue() methods, which returns me {password} and {username} as expected. However it breaks at String replace = h.replaceValues(h.xmlToString(), hmap) line. Any solutions please? It's worth mentioning that if i replace {password} with a random value (for example "password1") the code above works without issues.

0

1 Answer 1

6

The replaceAll method uses regular expressions, with { and } having special meaning. If you use replace(String, String) instead they're treated as normal Strings and there is no such issue.

Sign up to request clarification or add additional context in comments.

3 Comments

And despite the confusing name replaceAll() implying "not all" behaviour for replace(), replace() does in fact replace all occurrences.
maybe you could add a reference to Pattern.quote(String), but using replace(String, String) is probably the better solution since there is apparently no need for regular expressions, actually could be error prone to use it
Thanks for the answer!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.