替换所有匹配内容 Java 正则表达式
javaobject oriented programmingprogramming更新于 2025/2/13 17:48:17
一旦您编译了所需的正则表达式,并通过将输入字符串作为参数传递给 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+";
//创建一个 Pattern 对象
Pattern pattern = Pattern.compile(regex);
//匹配字符串中的编译模式
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);
}
}
输出
Enter input text: sample text with tab spaces No.of matches: 4 结果: 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";
//创建一个 Pattern 对象
Pattern pattern = Pattern.compile(regex);
//匹配字符串中的编译模式
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);
}
}
输出
Enter input text: test data 1 2 3 No.of matches: 3 结果: test data # 2 3
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

