简体   繁体   English

使用Java replaceAll方法用一个正则表达式替换句子中的单词

[英]Using java replaceAll method to replace word in sentences with one regex

I am trying to replace the "is" with "is not" in string but there is the exception that it should not replace "is" which is reside in other word. 我正在尝试用字符串“ is not”替换“ is”,但是有一个例外,那就是它不应该替换换句话说就是“ is”。

Example

"This is an ant" --> "This is not an ant" [CORRECT]
"This is an ant" --> "This not is not an ant" [INCORRECT]

So far, what I did is 到目前为止,我所做的是

String result = str.replaceAll("([^a-zA-Z0-9])is([^a-zA-Z0-9])","$1is not$2");
result = result.replaceAll("^is([^a-zA-Z0-9])","is not$1");
result = result.replaceAll("([^a-zA-Z0-9])is$","$1is not");
result = result.replaceAll("^is$","is not");

But I think it is possible with only one regex but I can't figure it out. 但是我认为只有一个正则表达式是可能的,但我无法弄清楚。 Is it possible? 可能吗?

Use word boundary ( \\b ): 使用单词边界( \\b ):

result = str.replaceAll("\\bis\\b", "is not");

NOTE: \\ should be escaped. 注意: \\应转义。 Otherwise it matches backspace (U+0008). 否则,它匹配退格键(U + 0008)。

See Demo . 参见演示

result = str.replaceAll("\\bis\\b", "is not");

\\b matches word-boundaries. \\b匹配单词边界。

[Edit]: Thanks @Falsetru for the notice on escaping - you're right, of course! [编辑]:感谢@Falsetru提供有关转义的通知-您当然是对的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM