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



Home Regularexpressions Replacing the first subsequence of the input

 
 

Share on Google+Share on Google+

Replacing the first subsequence of the input

Advertisement
This Example describes the way to replace only the first subsequence of the String using regular expression. For this we are going to make program named Replace_First.java.

Replacing the first subsequence of the input

     

This Example describes the way to replace only the first subsequence of the String using regular expression. For this we are going to make program named Replace_First.java. The steps involved in program Replace_First.java are described below:-

Pattern pattern = 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 = pattern.matcher(text):-Creates a matcher for matching the given input against pattern p.

matcher.replaceFirst("Java"):-This method will replace only the first occurrence of the input against the given pattern.

 

 

 

Replace_First.java:-

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

public class Replace_First {

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

Output of the program:-

Text before replacing first subsequence is:-kavaSun's regex library Kava is now kava
Text after replacing first subsequence is:-JavaSun's regex library Kava is now kava

DownLoad Source Code

Advertisements

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

Related Tutorials

Discuss: Replacing the first subsequence of the input  

Post your Comment


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