你将如何消毒' $'和' /'在字符串(java)

时间:2015-08-24 20:38:56

标签: java string design-patterns

难以清理字符串以允许$和/保持在字符串中。 (即希望接受姓名/电子邮件以保留美元符号)。为此,我试图使用Pattern类,并且我试图找到将Pattern方法放在公共String cutomiseText中的最佳解决方案。

//原始代码有效:

public String customiseText(String bodyText, List<Object> objectList) {
    Map<String, String> replaceKeyMap = extractMapFromList(objectList);

    // iterate over the mapkey and return the body text replace
    for (final String key : replaceKeyMap.keySet()) {
        String replacementKey = "(?i)" + key;
        String replacementValue = replaceKeyMap.get(key);
        if (replacementValue == null) {
            replacementValue = "";
        }
        bodyText = bodyText.replaceAll(replacementKey, replacementValue);
    }

    return bodyText;
}

//不起作用的代码:

import java.util.regex.Pattern;

public String customiseText(String bodyText, List<Object> objectList) {
    Map<String, String> replaceKeyMap = extractMapFromList(objectList);
    String escapedString = Pattern.quote(bodyText); //
    // iterate over the mapkey and return the body text replace
    for (final String key : replaceKeyMap.keySet()) {
        String replacementKey = "(?i)" + key; // not case sensitive and empty string matcher
        String replacementValue = replaceKeyMap.get(key);
        if (replacementValue == null) {
            replacementValue = "";
        }
        escapedString = escapedString.replaceAll(replacementKey, replacementValue);
    }

    return escapedString;
}

1 个答案:

答案 0 :(得分:1)

决定回到原始代码并添加一行来清理$ /:

// iterate over the mapkey and return the body text replace
for (final String key : replaceKeyMap.keySet()) {
    String replacementKey = "(?i)" + key;
    String replacementValue = replaceKeyMap.get(key);
    if (replacementValue == null) {
        replacementValue = "";
    }
    *replacementValue = replacementValue.replace("\\",     
        "\\\\").replace("$","\\$"); // sanitizes '$' and '\'* //only added this
    bodyText = bodyText.replaceAll(replacementKey, replacementValue);
}

return bodyText;

}