Matcher replaceFirst() 方法在 Java 中的用法与示例


java.util.regex.Matcher 类表示执行各种匹配操作的引擎。此类没有构造函数,可以使用 java.util.regex.Pattern 类的 matches() 方法创建/获取此类的对象。

此 (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 = "[#]";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Creating a Matcher object
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count++;
      }
      //Retrieving Pattern used
      System.out.println("The are character # occurred "+count+" times in the given text");
      //Replacing the first occurrence with @
      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 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[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      String regex = "\s+";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Retrieving the matcher object
      Matcher matcher = pattern.matcher(input);
      //Replacing all space characters with single space
      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

更新于: 20-Nov-2019

178 次浏览

职业生涯快起步

完成课程即可获得认证

开始学习
广告