Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to replace whole word with Word Boundaries in Java?

    • 0
    • 1
    • 0
    • 1
    • 0
    • 0
    • 0
    • 0
    • 1.02k
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: