正则表达式,提取带编号的列表(多行)

3

我得到了以下文本:

1. This is a text
where each item can span over multiple lines
2. that I want to
extract each seperate
item from
3. How can I do that?

我在Refiddle中尝试了这个正则表达式:

/([\d]+\.)(.*)/s

但我不确定它是贪婪的(只返回一个项)还是提取所有项。但当我在C#中尝试时,正则表达式没有匹配到任何内容。我做错了什么?更新:它是贪婪的,但由于.NET似乎无法使用\s,所以它没有起作用。我可以自己修复行尾(因为它们被剥离了)。但是,如何使正则表达式不贪婪呢?可以说类似于“匹配数字+点,然后取除下个数字+点之外的所有内容”吗?

这在很大程度上取决于你如何尝试。请向我们展示你的代码。 - Leri
我已经尝试过使用MultiLine选项和不使用它。我已经尝试过使用Replace()(使用回调重载)和Match()以及两者之间的所有组合。 - jgauffin
我喜欢regexlib.net网站上的正则表达式测试工具,可以用来测试一些正则表达式。 - Steve B
@PLB:再看一遍。你只打印了每个项目的第一行... - jgauffin
@DmitryDovgopoly:不,它不会。它很贪心。所有内容都在一个匹配中处理。 - jgauffin
显示剩余2条评论
1个回答

8
string input = @"1. This is a text
    where each item can span over multiple lines
    2. that I want to
    extract each seperate
    item from
    3. How can I do that?";
string pattern = @"([\d]+\. )(.*?)(?=([\d]+\.)|($))";
var matches = Regex.Matches(input, pattern, RegexOptions.Singleline);

foreach(Match match in matches)
{
    Console.WriteLine(match.Groups[2].Value);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接