Home Regularexpressions Replacing String using Regularexpression



Replacing String using Regularexpression
Posted on: August 26, 2008 at 12:00 AM
This Example describe the way to replace a String using Regularexpression.

Replacing String using Regularexpression

     

This Example describe the way to replace a String using Regularexpression. The steps involved in replacing a String are described below:

import java.util.regex.Matcher:-Matcher is a class that performs operation character sequence by using pattern.

import java.util.regex.Pattern:-Pattern is a class which is the compiled representation of a regularexpression.

String reg = "[0-9b-c]":-Regular expression for excluding digit from 1 to 9 , and letters from b to c.

Pattern pattern = Pattern.compile(reg):-Creates a pattern object and compiles the given regular expression into a   pattern.

Matcher matcher = pattern.matcher(text):-Creates a matcher that will match the given i nput against this pattern.

matcher.appendReplacement(buffer,replacingtext):- This method is a non-terminal append-and-replace step.

matcher.appendTail(buffer):-This method is a terminal append-and-replace step.

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

public class RegularExpressionReplace {
  public static void main(String[] args) {
  String reg =  color="#2a00ff">"[0-9b-c]";
  String text = "bcbcbcbbbbRbbboccbcbscbbbeibbndccibba" +
  ".nbbebbtbbpbbvbbtbb.bbtccdcc" +
   " 1232 4 4545454 4545 454 5465 4";
  String replacingtext = "";
  System.out.println("Text before replacing is:-"+"\n"+text);
  Pattern pattern = Pattern.compile(reg);
  Matcher matcher = pattern.matcher(text);
  StringBuffer buffer = new StringBuffer();
  while (matcher.find()) {
  matcher.appendReplacement(buffer,replacingtext);
  }
  matcher.appendTail(buffer);
  System.out.println("====================================");
  System.out.print("Text after replacing is:-");
  System.out.println(buffer.toString());
  }
}

output  of the program:-
Text before replacing is:-
bcbcbcbbbbRbbboccbcbscbbbeibbndccibba.nbbebbtbb
pbbvbbtbb.bbtccdcc 1232 4 4545454 4545 454 5465 4
====================================
Text after replacing is:-Roseindia.netpvt.td

Download Source Code

Related Tags for Replacing String using Regularexpression:
cstringioreplaceexpressionusingthisexampletoexpressexamssiedesreplulceinmtraceesdescribexaxampsessismplpresspreepleplarstrxpscrssriringthstpleplprono


More Tutorials from this section

Ask Questions?    Discuss: Replacing String using Regularexpression  

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.