难以清理字符串以允许 $ 和/留在字符串中。 (即想要接受姓名/电子邮件以保留美元符号)。为此,我尝试使用 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;
}
最佳答案
假设您的问题是 key
和 value
都是纯文本,而不是正则表达式,您必须转义(也称为“引用”)它们。
注意:更改了代码以使用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/