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

如何用更简便的方法按多个换行符对字符串分组?

解决方案:按双换行符分组文本行

方法1:字符串分割+简单遍历(最直观)

先统一换行符格式,再按双换行分割成块,最后将每个块拆分为单行并过滤空内容:

string input = @"a
b

c
d

e
f
g

h";

// 统一换行符为\n,兼容Windows(\r\n)和Unix(\n)格式
var normalizedInput = input.Replace("\r\n", "\n");
// 按双换行分割成独立块,移除空块
var blocks = normalizedInput.Split(new[] { "\n\n" }, StringSplitOptions.RemoveEmptyEntries);
// 将每个块拆分为单行,过滤空行(避免分割后出现空白内容)
var result = blocks.Select(block => 
    block.Split('\n').Where(line => !string.IsNullOrWhiteSpace(line)).ToList()
).ToList();

方法2:正则表达式匹配

利用正则匹配连续非空行组成的块,注意启用单行模式让.匹配换行符:

string input = @"a
b

c
d

e
f
g

h";

var normalizedInput = input.Replace("\r\n", "\n");
// 匹配被双换行或文本首尾包裹的连续行块
var regex = new Regex(@"(?<=^|\n\n)(.*?)(?=\n\n|$)", RegexOptions.Singleline);
var result = regex.Matches(normalizedInput)
                  .Cast<Match>()
                  .Select(match => 
                      match.Value.Split('\n').Where(line => !string.IsNullOrWhiteSpace(line)).ToList()
                  ).ToList();

方法3:LINQ Aggregate累积分组

通过LINQ的Aggregate方法逐行处理,按空行(双换行的拆分结果)划分分组:

string input = @"a
b

c
d

e
f
g

h";

var normalizedInput = input.Replace("\r\n", "\n");
var allLines = normalizedInput.Split('\n').ToList();

var result = allLines.Aggregate(new List<List<string>>(), (groups, line) =>
{
    if (string.IsNullOrWhiteSpace(line))
    {
        // 遇到空行,仅当最后一个分组非空时新建空分组(避免连续空行产生多个空组)
        if (groups.Count == 0 || groups.Last().Count > 0)
        {
            groups.Add(new List<string>());
        }
    }
    else
    {
        // 遇到非空行,若当前无分组或最后一个分组为空,则新建分组
        if (groups.Count == 0 || groups.Last().Count == 0)
        {
            groups.Add(new List<string>());
        }
        groups.Last().Add(line);
    }
    return groups;
})
// 过滤掉空分组
.Where(group => group.Count > 0)
.ToList();

注意事项

  • 优先统一换行符格式,避免因操作系统差异(\r\n vs \n)导致分割错误;
  • 所有方法都加入了空行过滤逻辑,避免处理输入中可能存在的空白行或分割残留的空内容。

内容的提问来源于stack exchange,提问作者hxsh.fx

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 22:15:30