C# 中的正则表达式匹配和拆分字符串

Regex match and split string in C#

我有一些格式如下的 ASCII 文件:

[section heading]
paragraphs......

[section heading]
paragraphs......
...

Note: heading text are always enclosed in some specific pattern (e.g. [ ] in the above example)

我想将文件分成单独的部分(每个部分都有一个 标题 内容 )。

解析上述文档的最有效方法是什么?

使用Regex.Match()我可以提取标题,但不能提取后续的文本内容。

使用 Regex.Split() 我可以抓取内容,但不能抓取相关标题。

是否可以结合这两种Regex方法来解析文档?有没有更好的方法来实现同样的目标?

试试这个:

string search = "\[([\w ]+)\]([^\[]*)";
foreach (Match match in Regex.Matches(yourtext, search))
    {
        string heading = match.Groups[1];
        string text = match.Groups[2];
    }

正则表达式捕获标题 段落。由于捕获组(在括号之间),您可以通过迭代匹配来提取它们。

(\[[^\]]*\])\n([\s\S]*?)(?=\n\[|$)

您可以尝试 this.Grab 组 1 和组 2.See 演示。

https://regex101.com/r/gU4aG0/1