【问题标题】:Illegal repetition exception when using String.replaceAll() method [duplicate]使用 String.replaceAll() 方法时出现非法重复异常 [重复]
【发布时间】:2017-06-04 01:20:39
【问题描述】:

我有以下代码:

    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 文件如下所示:

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

这会引发异常:非法重复。但我不知道如何转义“{}”字符,因为我得到这些字符的方法是使用 getKey() 和 getValue() 方法,它按预期返回 {password} 和 {username}。但是它在String replace = h.replaceValues(h.xmlToString(), hmap) 行中断。请问有什么解决办法吗?值得一提的是,如果我将 {password} 替换为随机值(例如“password1”),上面的代码就可以正常工作。

【问题讨论】:

    标签: java regex


    【解决方案1】:

    replaceAll 方法使用正则表达式,其中{} 具有特殊含义。如果您使用 replace(String, String) 代替,它们将被视为普通字符串并且不存在此类问题。

    【讨论】:

    • 尽管名称 replaceAll() 暗示 replace() 的“并非全部”行为令人困惑,但 replace() 实际上会替换所有出现的情况。
    • 也许您可以添加对Pattern.quote(String) 的引用,但使用replace(String, String) 可能是更好的解决方案,因为显然不需要正则表达式,实际上使用它可能容易出错
    • 感谢您的回答!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    • 2019-10-27
    • 1970-01-01
    相关资源
    最近更新 更多