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

طريقة Matcher replaceFirst() في Java مع أمثلة

هذافي java.util.regex.Matcherالنوع يمثل محركًا يقوم بمهام التطابق المختلفة. لا يحتوي هذا النوع على بناء هيكل، يمكن استخدامهmatches()The java.util.regex.Pattern method creates/gets an 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.

مثال 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 = "[#]";
      //创建一个模式对象
      Pattern pattern = Pattern.compile(regex);
      //创建一个Matcher对象
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count++;
      }
      //检索使用的模式
      System.out.println("The are character # occurred " + count + " times in the given text");
      //替换第一次出现的情况
      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 are character # occurred 5 times in the given text
Text after replacing the first occurrence of # with @
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[]) {
      //read string from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "\\s+";
      //compile regular expression
      Pattern pattern = Pattern.compile(regex);
      //retrieve matcher object
      Matcher matcher = pattern.matcher(input);
      //use a single space to replace all space characters
      String result = matcher.replaceFirst("_");
      System.out.print("Text after replacing the first space with '_': \n"+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