用另一个替换特定的字符串-String#replaceAll() [英] Replace specific string by another - String#replaceAll()
问题描述
我实际上是在开发一个解析器,并且陷入了一种方法的困境.
I'm actually developping a parser and I'm stuck on a method.
我需要清除某些句子中的特定单词,这意味着用空格或null
字符替换这些单词.
现在,我想到了以下代码:
I need to clean specifics words in some sentences, meaning replacing those by a whitespace or a null
character.
For now, I came up with this code:
private void clean(String sentence)
{
try {
FileInputStream fis = new FileInputStream(
ConfigHandler.getDefault(DictionaryType.CLEANING).getDictionaryFile());
BufferedReader bis = new BufferedReader(new InputStreamReader(fis));
String read;
List<String> wordList = new ArrayList<String>();
while ((read = bis.readLine()) != null) {
wordList.add(read);
}
}
catch (IOException e) {
e.printStackTrace();
}
for (String s : wordList) {
if (StringUtils.containsIgnoreCase(sentence, s)) { // this comes from Apache Lang
sentence = sentence.replaceAll("(?i)" + s + "\\b", " ");
}
}
cleanedList.add(sentence);
}
但是当我查看输出时,我发现sentence
中所有要替换的单词都由空格代替.
But when I look at the output, I got all of the occurences of the word to be replaced in my sentence
replaced by a whitespace.
有人能帮助我仅替换句子中要替换的确切单词吗?
Does anybody can help me out on replacing only the exact words to be replaced on my sentence?
提前谢谢!
推荐答案
您的代码中存在两个问题:
There are two problems in your code:
- 您丢失了
\b
之前字符串 - 如果文件中的任何单词带有特殊字符,您都会遇到问题
- You are missing the
\b
before the string - You will run into issues if any of the words from the file has special characters
要解决此问题,请按如下所示构造您的正则表达式:
To fix this problem construct your regex as follows:
sentence = sentence.replaceAll("(?i)\\b\\Q" + s + "\\E\\b", " ");
或
sentence = sentence.replaceAll("(?i)\\b" + Pattern.quote(s) + "\\b", " ");
这篇关于用另一个替换特定的字符串-String#replaceAll()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!