Java-Replace Operations

Replace Operations

Regular expressions are especially useful to replace text. Here are the available methods :

Method Description
replaceFirst(String replacement) Replaces the first matching part of the input stringwith replacement.
replaceAll(String replacement) Replaces every matching part of the input string with replacement.

The replaceAll( ) method of the Matcher object makes it easy to find and replace a String or a portion of String that is contained within a body of text. In order to use the replaceAll( ) method of the Matcher object, you must first compile a Pattern object by passing a regular expression String pattern to the Pattern.compile( ) method. Use the resulting Pattern object to obtain a Matcher object by calling its matcher( ) method. Once you have obtained a Matcher object, call its replaceAll( ) method by passing a String that you want to use to replace all the text that is matched by the compiled pattern.

For example, the following program replaces all occurrences of sequences “Symbian” with “Android”. Notice the original text is unchanged. The replaceAll method returns a modified text as a separate string.

Program



Program Source

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

public class Javaapp {
  
    public static void main(String[] args) {
        
        Pattern pat = Pattern.compile("Symbian");
        Matcher mat = pat.matcher("Galaxy A7(Symbian) Galaxy A8(Symbian)");
        String str = mat.replaceAll("Android");
        System.out.println(str);
    }
}

Leave a Comment