Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Regularexpressions Appending and replacing string using regular expression

 
 

Share on Google+Share on Google+

Appending and replacing string using regular expression

Advertisement
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

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 29, 2008

Related Tutorials

Discuss: Appending and replacing string using regular expression  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com