1

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?

2 Answers 2

5

Use word boundary (\b):

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

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

See Demo.

Sign up to request clarification or add additional context in comments.

Comments

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

\b matches word-boundaries.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.