Java-Search and Replace

Search and Replace

You can implement a search and replace operation very easily using regular expressions. Whenever you call the find() method for a Matcher object, you can call the appendReplacement( ) method to replace the subsequence that was matched. You create a revised version of the original string in a new StringBuffer object that you supply to the method. The arguments to the appendReplacement() method are a reference to the StringBuffer object that is to contain the new string, and the replacement string for the matched text.

For example, in the folowing program, ‘newstr’ is an empty StringBuffer object ready to receive  the revised text. Each call of appendReplacement( ) copies characters from ‘oldstr’ to ‘newstr’ starting at the character where the previous find() operation started and ending at the character preceding the first character matched, in other words. The method then appends the string specified by the second argument to ‘newstr’.

The find() method returns true three times, once for each occurrence of “adventure” in ‘oldstr’. When the three iteration have been completed, the find() method returns false on the next iteration, terminating the loop. All you now need to complete ‘newstr’ is a way to copy the text from ‘oldstr’ that comes after the last subsequence that was found. The appendTail( ) method for the Matcher object does that. This method copies the text starting with the mat.end( ) index position from the last successful match through to the end of the string. Thus this statement copies the segment “park.” from ‘oldstr’ to ‘newstr’.

Program

appendReplacement

Program Source

import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class Javaapp {
  
    public static void main(String[] args) {
        
        String oldstr = "Kruger adventure park\n" 
                      + "Chobe adventure park\n" 
                      +"Kgalagadi adventure park";
        
        Pattern pat = Pattern.compile("adventure");
        Matcher mat = pat.matcher(oldstr);
        
        StringBuffer newstr = new StringBuffer();
        
        while(mat.find())
        { 
            mat.appendReplacement(newstr, "national");
        }
        mat.appendTail(newstr);
        
        System.out.println(oldstr);
        System.out.println();
        System.out.println(newstr);
    }
}

Leave a Comment