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.
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.javacodeexamples.stringexamples; public class StringReplaceWholeWord { public static void main(String[] args) { String str = "I saw a cat at station"; str = str.replace("at", "on"); System.out.println(str); } } |
Output
1 |
I saw a con on stonion |
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”.
1 |
\\bat\\b |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package com.javacodeexamples.stringexamples; public class StringReplaceWholeWord { public static void main(String[] args) { String str = "I saw a cat at station"; String strPattern = "\\bat\\b"; str = str.replaceAll(strPattern, "on"); System.out.println(str); } } |
Output
1 |
I saw a cat on station |
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.