Java中具有示例的Matcher replaceAll()方法
该java.util.regex.Matcher中的类代表一个引擎,进行各种匹配操作。此类没有构造函数,可以使用matches()类java.util.regex.Pattern的方法创建/获取此类的对象。
在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 = "[#%&*]";
//创建一个模式对象
Pattern pattern = Pattern.compile(regex);
//创建一个Matcher对象
Matcher matcher = pattern.matcher(input);
int count =0;
while(matcher.find()) {
count++;
}
//检索使用的模式
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[]) {
//从用户读取字符串
System.out.println("Enter a String");
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("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