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.
How to replace a word in a sentence in java
You just need to place the word between word boundaries
Example:
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
Write a comment