You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何将字符串内同一正则模式的多次匹配项替换为不同值

实现方案

1. 原生Java实现

首先注意$在正则里是行尾匹配的特殊字符,所以匹配$?的时候需要对$做转义,常用两种实现方式:

方式一:使用Matcher类逐个匹配替换

适合替换次数不固定、需要动态判断替换内容的场景:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReplaceTest {
    public static void main(String[] args) {
        String original = "Hi$?Hello$?";
        // 正则中$是特殊字符,需要转义,所以正则表达式为\\$\\?
        Pattern pattern = Pattern.compile("\\$\\?");
        Matcher matcher = pattern.matcher(original);
        int replaceCount = 0;
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            replaceCount++;
            if (replaceCount == 1) {
                matcher.appendReplacement(sb, "there");
            } else if (replaceCount == 2) {
                matcher.appendReplacement(sb, "world");
            }
        }
        matcher.appendTail(sb);
        String result = sb.toString();
        // 输出结果:HithereHelloworld
        System.out.println(result);
    }
}

方式二:连续调用replaceFirst方法

适合替换次数固定且较少的场景,写法更简洁:

String original = "Hi$?Hello$?";
// replaceFirst第一个参数为正则,同样需要转义特殊字符$
String result = original.replaceFirst("\\$\\?", "there")
                        .replaceFirst("\\$\\?", "world");

2. Apache Commons StringUtils对应方法

Apache Commons Lang3的StringUtils工具类提供了replaceEach方法,可以直接实现按顺序替换多个占位符,无需处理正则转义:

import org.apache.commons.lang3.StringUtils;

public class StringUtilsReplaceTest {
    public static void main(String[] args) {
        String original = "Hi$?Hello$?";
        // 入参依次为:原字符串、待匹配的字符串数组、对应的替换值数组
        String result = StringUtils.replaceEach(original, new String[]{"$?", "$?"}, new String[]{"there", "world"});
        // 输出结果同样为HithereHelloworld
        System.out.println(result);
    }
}

注意:replaceEach是按普通字符串精确匹配,不会把搜索内容当作正则解析,特殊字符不需要额外转义,相比原生正则实现更简单安全。

内容的提问来源于stack exchange,提问作者Vishal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 01:18:00