Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace a word in a string using Java

Suppose I have the string "John is distinguished" and I wish to replace "is" with "FOO". When I use the replace methods, Java returns this string "John FOO dFOOtinguFOOhed" rather than the expected result, "John FOO distinguished". Java replaced every literal occurrence of "is" in the string with "FOO" which is not the intended result.

I would prefer not to invoke the replace method this way, replace(" is ", "FOO"), because any occurrence of "is" that is next to a punctuation or comma will be ignored. Example, calling replace this way with the input string "John is… distinguished" would result in the same string "John is… distinguished" rather than the correct output "John FOO… distinguished".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Can you try using regular expressions like the ff?

String string = "John is distinguished";
String result = string.replaceAll("\\bis\\b","FOO");

System.out.Println(result);

The "\\b" ensure that "is" is matched as whole word rather than just a part of the complete word, in a way ensure word boundary.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading