17

假设我有以下文本,我想提取“数字开头”和“数字结尾”之间的文本有动态数量的行和唯一改变其中数字的内容,例如:第一、第二等.我将从中提取数据的每个文件在“数字开头”和“数字结尾”之间的行数不同。如何编写正则表达式来匹配“数字开头”和“数字结尾”之间的内容,而不知道文件中有多少行介于数字开头和“数字结尾”之间?

问候!

This is the first line This is the second line

Start of numbers

This is the first line
This is the second line
This is the third line
This is the ...... line
This is the ninth line

End of numbers
4

4 回答 4

34

您应该使用SingleLine告诉您的 C# 正则表达式.匹配任何字符(不是除 之外的任何字符\n)的模式。

var regex = new Regex("Start of numbers(.*)End of numbers",
                  RegexOptions.IgnoreCase | RegexOptions.Singleline);
于 2012-04-24T05:37:58.783 回答
3

您应该能够毫无问题地匹配多行字符串。只要记住在 (\n换行) 中添加正确的字符。

string pattern = "Start of numbers(.|\n)*End of numbers";
Match m = Regex.Matches(input, pattern);

如果您能想到带有隐藏字符的字符串,这会更容易。

Start of numbers\n\nThis is the first line\nThis is the second line\n ...
于 2012-04-24T05:30:29.507 回答
0

像这样的东西:

^(开始)([\s\n\d\w]*)(结束)$

你在哪里得到第二组。如果您愿意,您甚至可以命名该组。所以重点是您在一个字符串中读取整个内容,然后从中获取正则表达式结果。

编辑:

必须稍微编辑一下。如果您的匹配项可能位于中间某处,则删除开始 (^) 和结束 ($) 字符。(开始)([\s\n\d\w]*)(结束)

请注意,这只会留下您想要获得的行。然后处理这些行。

于 2012-04-24T05:41:51.600 回答
0
/(?<=Start of numbers).*(?=End of numbers)/s

您需要启用 dotall 标志。

http://regexr.com?30oaj

于 2012-04-24T05:54:04.007 回答