Codementor Events

Replace the whole word with Word Boundaries in Java

Published Jun 25, 2019
Replace the whole word with Word Boundaries in Java

Now I am going to introduce to you If you - How to replace the whole word with Word Boundaries of your sentence in java. If you want to replace the whole word with the word boundaries in a string. Replace the word with Boundaries in Java. 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.

Exactly which characters are word characters depends on the regex flavor you're working with. In most flavors, characters that are matched by the short-hand character class \w are the characters that are treated as word characters by word boundaries. Java is an exception. Java supports Unicode for \b but not for \w. Quite similar as Javascript.

Boundary matchers help to find a particular word, but only if it appears at the beginning or end of a line. They do not match any characters. Instead, they match at certain positions, effectively anchoring the regular expression match at those positions. You can get more from here.

You can make your pattern matches more precise by specifying such information with boundary matchers. So now Let's take an example of replacing a word in a sentence in java.

package com.codingissue.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);
   }
}

The backslash from the boundary symbol must be escaped, hence the double-backslashes.

Output:

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

\B is the negated version of \b. \B matches at every position where \b does not. Effectively, \B matches at any position between two-word characters as well as at any position between two non-word characters.

Discover and read more posts from Amit Pandey (Coding Issue)
get started
post commentsBe the first to share your opinion
Show more replies