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.

Replacing the first subsequence of the input

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