Java String Replace Whole Word Only

Java String replace the whole word only example shows how to replace the whole word in a string instead of a partial match using word boundary regex in Java.

How to replace the whole word only in a string?

When we use the String replace method to replace text, it replaces all the matches it finds in the string including partial matches. Please see the below example to understand that.

Output

As you can see from the output, the replace method not only replaced the word “at”, but it also replaced the “at” characters inside the “cat” and “station” words.

In order to replace the whole word only, we need to use the regular expression (regex) pattern. The pattern should check for the word boundaries before and after the characters we want to replace so that it matches only with the whole words and ignores the partial matches inside other words.

Here is the regex pattern we can use to replace the whole word “at”.

The “\b” is a word boundary in regex. The word “at” is having the word boundary before and after it so that it will not match inside any other words.

Since we are going to replace using the regex pattern, we need to use the replaceAll method instead of the replace method. The replace method does not accept the regex, while the replaceAll method does.

Here is the example code that will only replace the whole word “at” in the string.

Output

As you can see from the output, this time only the whole word was replaced, and all the partial matches were ignored and kept as-is.

In short, we need to have “\b” before and after the word we want to replace, plus we need to use the replaceAll method instead of the replace method because it supports the regex pattern for the replacement.

If you want to learn more about the string, please visit the String Tutorial.

Please let me know your views in the comments section below.

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *