You need to enable JavaScript to run this app. 在C#中如何按注释符号分割文本文件并提取注释内容
优惠活动
大模型
产品
解决方案
定价
更多

在C#中如何按注释符号分割文本文件并提取注释内容

注释提取实现方案

核心思路

简单的字符串Split无法处理跨行块注释,也无法正确匹配成对的注释标记,用状态机逐字符遍历整个文件内容是最稳妥的实现方式,不需要逐行读取,处理跨行场景更简单。

示例实现(C#,匹配你用到的Split语法风格)

// 存储提取到的所有注释
List<string> commentList = new List<string>();
// 一次性读取整个代码文件内容
string codeContent = File.ReadAllText("你的目标代码文件路径");
int cursor = 0;
int contentLength = codeContent.Length;
// 标记当前是否处于块注释内部
bool inBlockComment = false;
StringBuilder currentCommentBuilder = new StringBuilder();

while (cursor < contentLength)
{
    if (!inBlockComment)
    {
        // 匹配单行注释起始标记 //
        if (cursor + 1 < contentLength && codeContent[cursor] == '/' && codeContent[cursor + 1] == '/')
        {
            cursor += 2;
            currentCommentBuilder.Clear();
            // 读取直到行尾
            while (cursor < contentLength && codeContent[cursor] != '\n' && codeContent[cursor] != '\r')
            {
                currentCommentBuilder.Append(codeContent[cursor]);
                cursor++;
            }
            // 首尾去空白后加入列表,不需要去空白可以去掉Trim()
            commentList.Add(currentCommentBuilder.ToString().Trim());
            // 跳过末尾的换行符
            while (cursor < contentLength && (codeContent[cursor] == '\n' || codeContent[cursor] == '\r'))
            {
                cursor++;
            }
        }
        // 匹配块注释起始标记 /*
        else if (cursor + 1 < contentLength && codeContent[cursor] == '/' && codeContent[cursor + 1] == '*')
        {
            inBlockComment = true;
            cursor += 2;
            currentCommentBuilder.Clear();
        }
        // 非注释区域直接跳过
        else
        {
            cursor++;
        }
    }
    else
    {
        // 匹配块注释结束标记 */
        if (cursor + 1 < contentLength && codeContent[cursor] == '*' && codeContent[cursor + 1] == '/')
        {
            inBlockComment = false;
            cursor += 2;
            // 把块注释内的换行替换为空格,和你给出的示例输出格式一致,不需要替换可以去掉Replace逻辑
            string blockComment = currentCommentBuilder.ToString()
                .Replace('\n', ' ')
                .Replace('\r', ' ')
                .Trim();
            commentList.Add(blockComment);
        }
        // 块注释内部逐字符存入缓存
        else
        {
            currentCommentBuilder.Append(codeContent[cursor]);
            cursor++;
        }
    }
}

补充说明

如果你的代码文件里存在字符串字面量包含//或者/*的场景,可以额外加一个inString状态做判断,避免把字符串里的内容误识别为注释,普通业务场景上面的代码完全可以满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 01:54:01