我试图从某个字符串中删除特定单词使用功能replace()或replaceAll()但这些删除即使它是一个字的一部分,这个词的所有出现!
例:
String content = "is not like is, but mistakes are common";
content = content.replace("is", "");
Run Code Online (Sandbox Code Playgroud)
输出: "not like , but mtakes are common"
期望的输出: "not like , but mistakes are common"
我怎样才能只替换字符串中的整个单词?
Hov*_*els 43
有没有搞错,
String regex = "\\s*\\bis\\b\\s*";
content = content.replaceAll(regex, "");
Run Code Online (Sandbox Code Playgroud)
请记住,您需要replaceAll(...)使用正则表达式,而不是replace(...)
\\b 给你一个词边界\\s* 在被删除的单词的任一侧消除任何空白区域(如果你想删除它).