[an error occurred while processing this directive]

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 is:-Roseindia.netpvt.td

Download Source Code


[an error occurred while processing this directive]