从字符串中删除特定单词

我正在尝试使用函数replace()replaceAll()删除某个字符串中的特定单词,但这些单词会删除所有出现的单词,即使它是另一个单词的一部分!

例:

 String content = "is not like is, but mistakes are common"; content = content.replace("is", ""); 

输出: "not like , but mtakes are common"

期望的输出: "not like , but mistakes are common"

我怎样才能只替换字符串中的整个单词?

有没有搞错,

 String regex = "\\s*\\bis\\b\\s*"; content = content.replaceAll(regex, ""); 

记住你需要使用replaceAll(...)来使用正则表达式,而不是replace(...)

  • \\b为您提供单词边界
  • \\s*消除被删除单词两侧的任何空白区域(如果你想删除它)。

content = content.replaceAll("\\Wis\\W|^is\\W|\\Wis$", "");

您可以尝试用“”替换“是”。 前面有一个空格,后面有一个空格,用一个空格代替。

更新:

为了使它适用于句子中的第一个“是”,也为“”做另一个“是”的替换。 用空字符串替换第一个和第一个空格。