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

Метод Matcher replaceFirst() с примерами в Java

Этотjava.util.regex.MatcherКласс представляет собой двигатель, выполняющий различные операции по соответствию. Этот класс не имеет конструктора и может быть использованmatches()Метод класса java.util.regex.Pattern создает/получает объект этого класса.

Этот класс (Matcher)replaceFirst()Метод принимает строковое значение и заменяет первое вхождение заданной строки в входном тексте, возвращает результат.

Пример 1

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++;
      }
      // Search pattern used
      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);
   }
}

Результат вывода

Enter input text:
Enter input text:
Hello# How # are# you # welcome to Tutorials#point
The character # occurred 5 times in the given text
Текст после замены первого occurrences of # на @
Hello@ How # are# you # welcome to Tutorials#point

Пример 2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceFirstExample {
   public static void main(String args[]) {
      //Чтение строки от пользователя
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "\\s+";
      //Компилировать регулярное выражение
      Pattern pattern = Pattern.compile(regex);
      //Извлечь объект маркера
      Matcher matcher = pattern.matcher(input);
      //С помощью одного пробела заменить все пробелы
      String result = matcher.replaceFirst("_");
      System.out.print("Text after replacing the first space with '_': \n"+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
Основной учебник
Рекомендуется к просмотру