您将如何清理字符串中的“$”和“/”(java)

how would you sanitize '$' and '/' in string (java)

难以清理字符串以允许 $ 和 / 保留在字符串中。 (即想接受 names/emails 以保留美元符号)。为此,我尝试使用 Pattern class 并试图找到将 Pattern 方法放置在 public 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;
}

假设您的问题是 keyvalue 都是纯文本,而不是正则表达式,您必须转义(又名 "quote")它们。

注意: 更改代码以使用 entrySet

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 (Entry<String, String> entry : replaceKeyMap.entrySet()) {
        String key = "(?i)" + Pattern.quote(entry.getKey());
        String value = entry.getValue();
        value = (value != null ? Matcher.quoteReplacement(value) : "");
        bodyText = bodyText.replaceAll(key, value);
    }
    return bodyText;
}

返回原始代码解决并添加一行以清理 $ / :

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

}