Big Data and Hadoop Training @$80 or Rs. 6,000 only - valid till Oct 17th Apply Now!

Appending and replacing string using regular expression

Ads
 

Appending and replacing string using regular expression

This Example describes the way to append the String with the existing one using expression.

This Example describes the way to append the String with the existing one using expression.

Appending and replacing string using regular expression

     

This Example describes the way to append the String with the existing one using expression. For this we are going to make program named Appendreplacement.java. 

The steps involved in program Appendreplacement.java are described below:-
Pattern pattern = Pattern.compile("(Rose) (.net)"):-
Creating a pattern object and compiling the given regular expression into a pattern. Here string "india"  is the text to be placed between ((Rose) and (.net)).

String text = "Company in Rohini: Rose .net.": Declaring String where the text is to be appended.

m.appendReplacement(buffer, replacement): This is the append and replace step of the Matcher class.

Appendreplacement.java

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

public class Appendreplacement {

  public static void main(String args[]) {
  Pattern pattern = Pattern.compile("(Rose) (.net)");
  StringBuffer buffer = new StringBuffer();

  String text = "Company in Rohini:- Rose .net.";
  System.out.println("Text before replacement is:" + text);
  String replacement = "$1india $2";

  Matcher m = pattern.matcher(text);
  m.find();

  m.appendReplacement(buffer, replacement);

  String str = buffer.toString();
  System.out.println("Text before replacement is:" + str);
  }
}

Output of the program:-

Text before replacement is:Company in Rohini:- Rose .net.
Text before replacement is:Company in Rohini:- Roseindia .net

DownLoad Source Code

Ads

Ads