用 Java 正则表达式替换所有匹配的内容
一旦你编译所需正则表达式并通过将输入字符串作为参数传递给 matcher() 方法来检索匹配器对象。
可以使用 Matcher 类的方法 replaceAll(),将输入字符串的所有匹配部分替换为另一个字符串。
此方法接受一个字符串(替换字符串),并将输入字符串中的所有匹配项替换为它,并返回结果。
示例 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAll{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "\t+";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("No.of matches: "+count);
String result = matcher.replaceAll(" ");
System.out.println("Result: "+result);
}
}输出
Enter input text: sample text with tab spaces No.of matches: 4 Result: sample text with tab spaces
同样,你可以使用 Matcher 类的 replaceFirst() 方法来替换第一个匹配项。
示例 2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReplaceAll{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input text: ");
String input = sc.nextLine();
String regex = "\d";
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("No.of matches: "+count);
String result = matcher.replaceFirst("#");
System.out.println("Result: "+result);
}
}输出
Enter input text: test data 1 2 3 No.of matches: 3 Result: test data # 2 3
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP