从字符串中删除特定单词 [英] Remove a specific word from a string
本文介绍了从字符串中删除特定单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用函数 replace()
或 replaceAll()$ c $从某个字符串中删除特定单词c>但这些删除了这个单词的所有出现,即使它是另一个单词的一部分!
I'm trying to remove a specific word from a certain string using the function replace()
or replaceAll()
but these remove all the occurrences of this word even if it's part of another word!
示例:
String content = "is not like is, but mistakes are common";
content = content.replace("is", "");
输出: 不喜欢,但是mtakes很常见
所需的输出: 不喜欢,但错误很常见
如何只替换字符串中的整个单词?
How can I substitute only whole words from a string?
推荐答案
哎呀,
String regex = "\\s*\\bis\\b\\s*";
content = content.replaceAll(regex, "");
请记住你需要使用 replaceAll(...)
使用正则表达式,而不是替换(...)
Remember you need to use replaceAll(...)
to use regular expressions, not replace(...)
-
\\b
为您提供单词边界 -
\\\\ *
删除要删除的单词两侧的任何空格(如果你想删除它)。
\\b
gives you the word boundaries\\s*
sops up any white space on either side of the word being removed (if you want to remove this too).
这篇关于从字符串中删除特定单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文