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



Home Regularexpressions Replacing all the text of String using expression

 
 

Share on Google+Share on Google+

Replacing all the text of String using expression

Advertisement
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

     

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

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 30, 2008

Related Tutorials

Discuss: Replacing all the text of String using expression  

Post your Comment


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