English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Matcher replaceFirst() method with examples in Java

Thejava.util.regex.MatcherThis class represents an engine that performs various matching operations. The class has no constructor, and it can be used withmatches()The method of the class java.util.regex.Pattern creates/gets the object of the class.

This (Matcher) classreplaceFirst()The method accepts a string value and replaces the first matching substring in the input text with the given string value, and returns the result.

Example1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceFirstExample {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input text: ");
      String input = sc.nextLine();
      String regex = "[#]";
      //Create a Pattern object
      Pattern pattern = Pattern.compile(regex);
      //Create a Matcher object
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         ++;
      }
      //The pattern used for search
      System.out.println("The character # occurred ");++" times in the given text
      //Replace the first occurrence
      String result = matcher.replaceFirst("@");
      System.out.println("Text after replacing the first occurrence of # with @ \n");+result);
   }
}

Output Result

Enter input text:
Enter input text:
Hello# How # are# you # welcome to Tutorials#point
The character # occurred 5 times in the given text
Text after replacing the first occurrence of # with @
Hello@ How # are# you # welcome to Tutorials#point

Example2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceFirstExample {
   public static void main(String args[]) {
      //Read a string from the user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "\\s+";
      //Compile the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieve the matcher object
      Matcher matcher = pattern.matcher(input);
      //Replace all space characters with a single space
      String result = matcher.replaceFirst("_");
      System.out.print("Text after replacing the first space with '_': 
"+result);
   }
}

Output Result

Enter a String
hello this is a sample text with irregular spaces
Text after replacing the first space with '_':
hello_this is a sample text with irregular spaces