How to replace whole word with Word Boundaries in Java?

how to replace a word in a sentence in java

How to replace a word in a sentence in java

If you want to replace the whole word with the word boundaries in a string. For this, we use "\b" regular expression token which is called a word boundary. It usually matches at the start or the end of a word.

Example: You just need to place the word between word boundaries

package com.legendblogs.test;
public class TestApps {
/*
*@param args
*/
public static void main(String[] args){
String s = "A man is an Ironman like manpower";
//It will replace if the first character is a word character or not
String d = s.replaceAll("\\bman", "tony");
System.out.println(d);
//It will replace if if the last character is a word character or not
String b = s.replaceAll("man\\b", "tony");
System.out.println(b);
//It will replace whole word only
String c = s.replaceAll("\\bman\\b", "tony");
System.out.println(c);
}
}

Output:

A tony is an Ironman like tonypower
A tony is an Irontony like manpower
A tony is an Ironman like manpower