gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:25:52 25 4
gpt4 key购买 nike

难以清理字符串以允许 $ 和/留在字符串中。 (即想要接受姓名/电子邮件以保留美元符号)。为此,我尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com