Use word boundary (\b
):
result = str.replaceAll("\\bis\\b", "is not");
NOTE: \
should be escaped. Otherwise it matches backspace (U+0008).
See Demo.
Question
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?
Solution
Use word boundary (\b
):
result = str.replaceAll("\\bis\\b", "is not");
NOTE: \
should be escaped. Otherwise it matches backspace (U+0008).
See Demo.
OTHER TIPS
result = str.replaceAll("\\bis\\b", "is not");
\b
matches word-boundaries.
[Edit]: Thanks @Falsetru for the notice on escaping - you're right, of course!