Sometimes we need to replace 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.demo;
public class TestApps {
/*
*@param args
*/
public static void main(String[] args){
String s = "one dog two catsdog dogCats in the field";
//It will replace if the first character is a word character or not
String d = s.replaceAll("\\bdog", "#@!*");
System.out.println(d);
//It will replace if if the last character is a word character or not
String b = s.replaceAll("dog\\b", "#@!*");
System.out.println(b);
//It will replace whole word only
String c = s.replaceAll("\\bdog\\b", "#@!*");
System.out.println(c);
}
}
Output:
one #@!* two catsdog #@!*Cats in the field
one #@!* two cats#@!* dogCats in the field
one #@!* two catsdog dogCats in the field
Hope this will help:)
0 Comment(s)