Java中Matcher replaceAll()方法,附示例


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("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 "+count+" special characters [# % & *] in the given text");
      //Replacing all special characters [# % & *] with ! String result = matcher.replaceAll("!");
      System.out.println("Replaced all special characters [# % & *] with !: \n"+result);
   }
}

输出

Enter input text:
Hello# How # are# you *& welcome to T#utorials%point
The are 7 special characters [# % & *] in the given text
Replaced all special characters [# % & *] with !:
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[]) {
      //Reading String from user
      System.out.println("Enter a String");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //Regular expression to match spaces (one or more)
      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.replaceAll(" ");
      System.out.print("Text after removing unwanted spaces: \n"+result);
   }
}

输出

Enter a String
hello this is a sample text with irregular spaces
Text after removing unwanted spaces:
hello this is a sample text with irregular spaces

更新于: 2019 年 11 月 20 日

3K+ 浏览

开启你的 职业生涯

完成课程获得认证

开始
广告