Skip to main content
 首页 » 编程设计

c#之正则表达式题: Until next match OR End Of Document

2024年01月25日27虾米姐

我正在开发一个文档解析器,以从我收到的一些文档中提取数据,并且我正在使用 C# 进行编码。文件的形式是:

 
(Type 1): (potentially multi-lined string) 
(Type 2): (potentially multi-lined string) 
(Type 3): (potentially multi-lined string) 
... 
(Type N): (potentially multi-lined string) 
(Type 1): (potentially multi-lined string) 
... 
End Of Document. 

文档以相同格式重复(Type 1)-(Type N)M次

我在处理多行字符串时遇到问题,无法找到 (Type 1)-(Type N) 的最后一次迭代

我需要做的是将(可能是多行字符串)捕获到一个由其前导(类型#)命名的组中

这是我尝试匹配的文档片段:

Name: John Dow 
Position: VP. over Development 
Bio: Here is a really long string of un important stuff 
that could include words like "Bio" or "Name".  Some times I have problems 
here, but for the most part it should be normal Bio information 
Position History: Vp. over Development 
Sr. Project Manager 
Jr. Project Manager 
Developer 
Peon 
Notes: Here are some notes that may or may not be multilined 
and if it is, all the lines need to be captured for this person. 
Name: Joe Noob 
Position: Peon 
Bio: I'm a peon, so I have little bio 
Position History: Peon 
Notes: few notes 
Name: Jane Smith 
Position: VP. over Sales 
Bio: Here is a really long string of more un important stuff 
that could include words like "Bio" or "Name".  Some times I have problems 
here, but for the most part it should be normal Bio information 
Position History: Vp. over Sales 
Sales Manager 
Secretary 
Notes: Here are some notes that may or may not be multilined 
and if it is, all the lines need to be captured for this person. 



(type #) 的顺序始终相同,并且它们前面总是有一个换行符。

我有什么:

Name:\s(?:(?.*?)\r\n)+?Position:\s(?:(?.*?)\r\n)+?Bio:\s(?:(?.*?)\r\n)+?Position History:\s(?:(?.*?)\r\n)+?Notes:\s(?:(?.*?)\r\n)+? 



任何帮助都会很棒!

请您参考如下方法:

因为您使用的是惰性匹配,所以最后一个标记只需要它必须的那么多。您可以通过在模式末尾添加 lookahed 来解决该问题,以匹配直到下一个标记:

(?=^Name:|$) 

这是完整的正则表达式:

Name:\s(?:(.*?)\s+)Position:\s(?:(.*?)\s+)Bio:\s(?:(.*?)\s+)Position History:\s(?:(.*?)\s+)Notes:\s(?:(.*?)\s+)(?=^Name:|$) 

示例:http://regexhero.net/tester/?id=92982feb-806f-4d0a-96a3-5ef6689a0e01