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

如何在Java预处理中折叠C风格块注释并保留换行维持行号?

解决C风格块注释折叠时保留原代码行号的问题

原方案直接将整个块注释替换为空字符串,会丢失注释内的换行导致行号偏移。要实现折叠注释同时保留行号,核心是保留注释中的所有换行,仅移除非换行的注释内容,具体实现如下:

实现思路

  • 遍历匹配到的每一个块注释
  • 统计当前注释内容中包含的换行符数量
  • 将该注释替换为对应数量的换行符,确保处理后的代码行数与原代码完全一致

代码实现

Java 11+ 版本(使用String.repeat())

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

public class CommentProcessor {
    public static String processComments(String sourceCode) {
        String open = "/\\*";  // 转义后的/*
        String body = "(.*?)";
        String close = "\\*/"; // 转义后的*/
        Pattern commentPattern = Pattern.compile(open + body + close, Pattern.DOTALL);
        Matcher matcher = commentPattern.matcher(sourceCode);
        
        StringBuilder result = new StringBuilder();
        while (matcher.find()) {
            String fullComment = matcher.group(0);
            // 统计注释中的换行符数量
            long newlineCount = fullComment.chars().filter(c -> c == '\n').count();
            // 生成对应数量的换行符作为替换内容
            String replacement = "\n".repeat((int) newlineCount);
            matcher.appendReplacement(result, replacement);
        }
        matcher.appendTail(result);
        return result.toString();
    }
}

Java 8 及以下版本(手动构建换行字符串)

如果项目使用Java 8或更低版本,替换String.repeat()部分为手动循环:

// 替换上述代码中的replacement生成逻辑
StringBuilder replacementBuilder = new StringBuilder();
for (int i = 0; i < newlineCount; i++) {
    replacementBuilder.append('\n');
}
String replacement = replacementBuilder.toString();

效果说明

  • 单行注释/* 这是单行注释 */:内部无换行,替换为空字符串,原代码行数不变
  • 多行注释:
    /*
      多行注释第一行
      多行注释第二行
    */
    
    注释内包含2个换行符,替换为"\n\n",处理后仍保留3行空行,与原注释的行数完全一致,确保后续编译错误的行号能精准对应原代码位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:20:31