【发布时间】:2019-12-09 19:06:33
【问题描述】:
我正在阅读一份文档并删除其中的一些字词。 我有以下功能:
//Takes a string and removes the word
private static String removeWord(String string, String word) {
if (string.contains(word)) {
String tempWord = word.trim();
string = string.replaceAll(tempWord, "");
}
return string;
}
例如,当我尝试替换时遇到以下问题:
Hello world (
给我以下错误:
原因:java.util.regex.PatternSyntaxException:索引 14 附近的未封闭组
做一些研究我发现这是因为split() 需要一个正则表达式,而括号用于标记正则表达式中的捕获组。
所以我这样做了:
private static String removeWord(String string, String word) {
if (string.contains(word)) {
String [] temp = word.split(" ");
word = "";
for (int i = 0; i < temp.length ; i++) {
if (temp[i].equals("(")){
word += " "+ "\\(";
}else if (temp[i].equals(")")){
word += " "+ "\\)";
} else {
word += temp[i] + " ";
}
}
String tempWord = word.trim();
string = string.replaceAll(tempWord, "");
}
return string;
}
此代码不是最佳解决方案。因为有时字符串就像(Hello world。
如何改进这部分代码?
【问题讨论】:
-
只需在将字符串提供给
.split方法之前使用Pattern.quote。