Replacing all the text of String using expression

This Example describes the way to Replace certain part of the whole String using regular expression. For this we are going to make program named Replaceall.java.

Replacing all the text of String using expression

Replacing all the text of String using expression

     

This Example describes the way to Replace certain part of the whole String using regular expression. For this we are going to make program named Replaceall.java. The steps involved in program Replaceall.java are described below:-

Pattern p = Pattern.compile("(k|K)ava"): Creating a pattern object and compiling the given regular expression into a pattern. Here 'k|K' means to replace all in place of character (k or K).

String text = "kavaSun's regex library Kava is now kava":- Declaring text in which character (K or k) is to be replaced by the matcher.

Matcher matcher = p.matcher(text):- Creates a matcher for matching the given input against pattern p.

matcher.replaceAll("Java"):- This method will replace every occurrence of the input against the given pattern.

Replaceall.java


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

public class Replaceall {

  public static void main(String args[]) {
  Pattern p = Pattern.compile("(k|K)ava");
  String text = "kavaSun's regex library Kava is now kava";
  System.out.println("Text before replacement is:"+text);
  Matcher matcher = p.matcher(text);
  String str = matcher.replaceAll("Java");
  System.out.println("Text after replacement is:"+str);
  }
}

Output of the program:-

Text before replacement is:kavaSun's regex library Kava is now kava
Text after replacement is:JavaSun's regex library Java is now Java


Download Source Code