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

Méthode replaceFirst() avec exemple en Matcher Java

Thejava.util.regex.MatcherThis class represents an engine, performing various matching operations. This class has no constructor, and it can be used withmatches()The method create of the class java.util.regex.Pattern/Get the object of this 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.

Exemple1

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()) {
         count++;
      }
      //Pattern used for search
      System.out.println("The character # occurred ");+count+" 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);
   }
}

Résultat de la sortie

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

Exemple2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceFirstExample {
   public static void main(String args[]) {}}
      //Lire une chaîne de l'utilisateur
      System.out.println("Saisissez une chaîne");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "\\s+";
      //Compiler l'expression régulière
      Pattern pattern = Pattern.compile(regex);
      //Récupérer l'objet du mécanisme de correspondance
      Matcher matcher = pattern.matcher(input);
      //Remplacez tous les caractères d'espace par un espace unique
      String result = matcher.replaceFirst("_");
      System.out.print("Texte après remplacement du premier espace par '_': \n"+result);
   }
}

Résultat de la sortie

Saisissez une chaîne
hello this is a sample text with irregular spaces
Texte après remplacement du premier espace par '_':
hello_this is a sample text with irregular spaces