简体   繁体   中英

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.

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 ):

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

NOTE: \\ should be escaped. Otherwise it matches backspace (U+0008).

See Demo .

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

\\b matches word-boundaries.

[Edit]: Thanks @Falsetru for the notice on escaping - you're right, of course!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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