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

Java如何替换指定标识对应大括号内的全部文本内容

Java 实现指定大括号块内容替换

核心实现逻辑

直接通过正则表达式匹配目标块结构完成替换,无需引入第三方解析库,核心规则:

  • 精准匹配test_two、test_three两个标识对应的大括号块,用非贪婪匹配避免跨块吞内容
  • 保留原有块名、大括号、缩进格式,仅替换大括号内部的文本

完整可运行代码

import java.util.regex.Pattern;

public class ContentReplace {
    public static void main(String[] args) {
        // 原始字符串,Java 15+支持文本块写法,低版本可替换为带\n转义的普通字符串
        String test = """
            test_one {
            Lorem Ipsum is simply dummy text of the printing and typesetting industry.
            }
            
            test_two {
            Lorem Ipsum is simply dummy text of the printing and typesetting industry.
            }
            
            test_three {
            Lorem Ipsum is simply dummy text of the printing and typesetting industry.
            }
            """;

        // 自定义替换内容
        String customText = "This is my text";

        // 正则说明:
        // 第一组捕获:块名前空白 + 目标块名 + 左大括号 + 左大括号后空白(含换行、缩进)
        // 中间匹配:括号内所有内容(含换行),非贪婪模式匹配到最近的右大括号
        // 第三组捕获:右大括号前空白 + 右大括号
        Pattern blockPattern = Pattern.compile("(\\s*(test_two|test_three)\\s*\\{\\s*)[\\s\\S]*?(\\s*\\})");
        
        String replaced = blockPattern.matcher(test).replaceAll(match -> {
            // 保留前后格式部分,中间插入自定义内容
            return match.group(1) + customText + match.group(3);
        });

        // 输出结果
        System.out.println(replaced);
    }
}

扩展说明

  • 如果需要新增替换的块名,直接在正则的test_two|test_three部分用竖线分隔追加块名即可
  • 如果不同块需要替换不同内容,在lambda表达式中通过match.group(2)获取当前匹配到的块名,按需返回对应替换内容即可
  • 非贪婪匹配规则[\s\S]*?会自动匹配对应块最近的闭合右大括号,不会出现块内容交叉匹配的问题,块之间存在空行也不影响匹配结果

内容的提问来源于stack exchange,提问作者Влад

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 22:18:13