我實際上正在開發一個解析器,而且我卡在一個方法上。用另一個替換特定的字符串 - String#replaceAll()
我需要清理某些句子中的特定單詞,這意味着用空格或null
字符來替換這些單詞。 現在,我想出了這個代碼:
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
更換。
有沒有人可以幫我取代只有我的句子被替換的確切單詞?
提前致謝!
'sentence.replaceAll( 「(我)\\ B'」 + S + 「\\ B」,「「);' - 你省略前導'\ B'字邊界。 –