Home Regularexpressions Appending and replacing string using regular expression



Appending and replacing string using regular expression
Posted on: August 29, 2008 at 12:00 AM
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

Related Tags for Appending and replacing string using regular expression:
cstringioexpressionusingappendthisappexamplewithtoexpressexamssieitdespeinmtrstiesendpenppdescribexaxampsessismplpresspreexistingstrxpxiscrssriringthbesstapexipleplprndono


More Tutorials from this section

Ask Questions?    Discuss: Appending and replacing string using regular expression  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.