Java 中的 Matcher replaceFirst() 方法示例

javaobject oriented programmingprogramming更新于 2024/5/8 12:28:17

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("输入输入文本:");
      String input = sc.nextLine();
      String regex = "[#]";
      //创建一个 Pattern 对象
      Pattern pattern = Pattern.compile(regex);
      //创建一个 Matcher 对象
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while(matcher.find()) {
         count++;
      }
      //检索使用的模式
      System.out.println("字符 # 在给定文本中出现了 "+count+" 次");
      //用 @ 替换第一次出现的位置
      String result = matcher.replaceFirst("@");
      System.out.println("将第一次出现的 # 替换为 @ 后的文本 \n"+result);
   }
}

输出

输入输入文本:
输入输入文本:
Hello# How # are# you #welcome to Tutorials#point
给定文本中出现的 # 字符有 5 次
将第一次出现的 # 替换为 @ 后的文本
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("输入字符串");
      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("将第一个空格替换为 '_' 后的文本:\n"+result);
   }
}

输出

输入字符串
hello this is a sample text with irregular space
将第一个空格替换为 '_' 后的文本:
hello_this is a sample text with irregular space

相关文章


有用资源