插件窝 干货文章 Java正则表达式匹配字符串替换方法详解

Java正则表达式匹配字符串替换方法详解

Java正则表达式 字符串替换 Pattern Matcher replaceAll    来源:    2025-08-02

Java正则表达式匹配字符串替换方法详解

在Java开发中,正则表达式是处理字符串匹配和替换的强大工具。本文将详细介绍Java中使用正则表达式进行字符串替换的各种方法。

1. String类的replaceAll方法

String类提供了最简单的正则表达式替换方法:

String str = "Hello 123 World 456";
String result = str.replaceAll("\\d+", "***");
// 输出:Hello *** World ***

2. Pattern和Matcher类

对于更复杂的替换需求,可以使用Pattern和Matcher类:

Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("Hello 123 World 456");
String result = matcher.replaceAll("***");

3. 使用Matcher的appendReplacement方法

需要更灵活控制替换过程时:

Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while(m.find()) {
    m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
// 结果:one dog two dogs in the yard

4. 正则表达式特殊替换

可以使用$n引用捕获组:

String str = "John Smith";
String result = str.replaceAll("(\\w+) (\\w+)", "$2, $1");
// 输出:Smith, John

常见问题解答

  • Q:如何替换所有匹配项?
    A:使用replaceAll()方法会自动替换所有匹配项
  • Q:如何只替换第一个匹配项?
    A:使用replaceFirst()方法
  • Q:替换时如何保留部分原内容?
    A:使用捕获组和$n引用

掌握这些Java正则表达式替换方法,可以大大提高字符串处理的效率和灵活性。