Skip to main content
 首页 » 编程设计

c#之正则表达式,提取编号列表(多行)

2024年02月13日29luoye11

我得到以下文本:

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# 中尝试时,正则表达式不匹配任何内容。

我做错了什么?

更新

它已经准备好了,但没有用,因为 \s 似乎在 .NET 中不起作用。我可以自己修复行尾(因为它们被剥离)。但是如何使正则表达式不贪心呢?是否可以这样说

匹配数字+点,然后取除下一个数字+点以外的所有内容?

请您参考如下方法:

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); 
}