-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.

user85421
  • 28,957
  • 10
  • 64
  • 87
Tudor
  • 199
  • 3
  • 14

1 Answers1

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.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • 3
    And despite the confusing name `replaceAll()` implying "not all" behaviour for `replace()`, `replace()` does in fact replace all occurrences. – Bohemian Jan 19 '17 at 11:07
  • 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 – user85421 Jan 19 '17 at 11:18
  • Thanks for the answer!! – Tudor Jan 19 '17 at 11:22