java - 你如何清理字符串中的 '$' 和 '/' (java)

标签 java string design-patterns

难以清理字符串以允许 $ 和/留在字符串中。 (即想要接受姓名/电子邮件以保留美元符号)。为此,我尝试使用 Pattern 类,并尝试找到将 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 都是纯文本,而不是正则表达式,您必须转义(也称为“引用”)它们。

注意:更改了代码以使用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;
}

关于java - 你如何清理字符串中的 '$' 和 '/' (java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32191350/

相关文章:

java - Glassfish 充斥着日志记录

java - 如何将字符串转换为 ArrayList?

string - 在scala中使用本地化对字符串列表进行排序

ios - 带有参数 iOS 的单例

ios - 为每个UITableViewCell创建 View 模型

java - 用于将请求最多的图像存储在 map 对象中的设计模式

java - 是否可以使用 JSON 发送文件

java - 检查Java中的MQ(websphere)连接

java - 防止 Spring 预填充字段

string - 为什么程序在分配字符串后崩溃