Share on Google+Share on Google+

Replacing String using Regularexpression

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 input 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.
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()) {
  System.out.print("Text after replacing is:-");

output  of the program:-
Text before replacing is:-
pbbvbbtbb.bbtccdcc 1232 4 4545454 4545 454 5465 4
Text after replacing

Download Source Code


Posted on: August 26, 2008 If you enjoyed this post then why not add us on Google+? Add us to your Circles

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.

Discuss: Replacing String using Regularexpression  

Post your Comment

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