Java 中的 Matcher replaceAll() 方法示例

javaobject oriented programmingprogramming更新于 2024/5/8 11:56:17

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

此 (Matcher) 类的 replaceAll() 方法接受字符串值,用给定的字符串值替换输入中所有匹配的子序列并返回结果。

示例 1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
   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.replaceAll("!");
      System.out.println("将所有特殊字符 [# % & *] 替换为 !:\n"+result);
   }
}

输出

输入文本:
Hello# How # are# you *& welcome to T#utorials%point
给定文本中有 7 个特殊字符 [# % & *]
将所有特殊字符 [# % & *] 替换为 !:
Hello! How ! are! you !! welcome to T!utorials!point

示例 2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAllExample {
   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.replaceAll(" ");
      System.out.print("删除不需要的空格后的文本:\n"+result);
   }
}

输出

输入字符串
hello this is a sample text with irregular space
删除不需要的空格后的文本:
hello this is a sample text with irregular space

相关文章


有用资源