Java Code to Find & Replace a Word in a String using regex with Matcher class example

Find & replace of a word in a line of string can be done in several ways. Already String class have  methods   replace and  replaceAll()  which replaces all occurrence of the given word to a new word. ReplaceAll( String regex,  String replacement ) method of String class replaces all occurrences of  a given string that matches the given regular expression with the given new string (i.e. replacement). The same thing can be done using Matcher class  also.

In this tutorial, let us see the steps to do using regular expression using Matcher Class:

1.Create a pattern to match the search string. //searchStr
2. Create a matcher with an input line of string // inputLine
3. Use Matcher.find() method to find the first occurrence of searchStr in inputLine (Note : Matcher class also has replaceAll method which can replace all occurrence of the given word to a new word shown in   method3 given below )
4. Use Matcher.appendReplacement() method to replace the searchStr with the new string creates a new stringBuffer object.
5. Continue step 3 until the last occurrence of the search string
6. Convert stringBuffer to String.

In the below code,

method1 replaces each  occurrence of the given string in the input string  with new string  using Matcher class and appendReplacement method using loop.

method2 gives the example for using replaceAll method of String class

method3 uses the replaceAll method of Matcher class to replace all occurrence of the given string to new string


package com.javaonline;

import java.util.regex.*;
import java.io.*;

public class FindReplace {
public static void main(String[] args)     throws Exception {

	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	System.out.println("Enter Line to search and replace");
	String inputLine=br.readLine();
	System.out.println("Enter String to search ");
	String searchStr=br.readLine();
	System.out.println("Enter String to replace");
	String repStr=br.readLine();

	System.out.println("Using Method1\n");
	method1(inputLine, searchStr, repStr);
	System.out.println("Using Method2\n");
	method2(inputLine, searchStr, repStr);
	System.out.println("Using Method3\n");
	 method3(inputLine, searchStr, repStr);
    }

    //Using Matcher class and appendReplacement method

private static void method1(String inputLine, String searchStr, String repStr)

 {
       Pattern p = Pattern.compile(searchStr);
        Matcher matcher = p.matcher(inputLine);
        boolean found = matcher.find();
        StringBuffer outputStrbuf = new StringBuffer();
        while(found) {
            matcher.appendReplacement(outputStrbuf, repStr);
           found = matcher.find();
        }
         matcher.appendTail(outputStrbuf); //Last portion after the last occurrence of the search string , is appended to the string buffer.
        System.out.println(outputStrbuf.toString()+"\n");
}

// Using replaceAll()  method of String Calss

private static void method2(String inputLine, String searchStr, String repStr)

 {

	  String  outputLine=inputLine.replaceAll(searchStr, repStr);
	  System.out.println(outputLine+"\n");
}

// Using replaceAll()  method of Matcher Calss

private static void method3(String inputLine, String searchStr, String repStr)

 {
       Pattern p = Pattern.compile(searchStr);
       Matcher matcher = p.matcher(inputLine);
       String output = matcher.replaceAll(repStr);
       System.out.println(output +"\n");
        //System.out.println(outputStrbuf.toString());
}

}

Output :

In the following example , all occurance of dog is replaced by cow by using three methods

find replace

Reference : Matcher Class

You may also like

Leave a Reply