正则表达式匹配变量多行?

让我说我有以下文字,我想提取“数字开头”和“数字结束”之间的文字有动态的线条数量和唯一的数字在其中的变化,例如:第一,第二等我将从中提取数据的每个文件在“数字开头”和“数字结束”之间有不同的行数。 如何编写正则表达式以匹配“数字开头”和“数字结束”之间的内容,而不知道数字起点和“结束数字”之间的文件中有多少行?

问候!

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 

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

 var regex = new Regex("Start of numbers(.*)End of numbers", RegexOptions.IgnoreCase | RegexOptions.Singleline); 

您应该能够匹配多行字符串而不会出现问题。 只需记住在( \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 ... 

像这样的东西:

^(开始)([\ S \ n \ d \ W] *)(结束)$

你得到第二组的地方。 如果您愿意,甚至可以为该组命名。 所以关键是你在一个字符串中读取整个内容然后从中获取regexp结果。

编辑:

必须编辑一下。 如果你匹配可以在某个地方的中间,那么删除开始(^)和结束($)字符。 (开始)([\ S \ n \ d \ W] *)(结束)

并且请注意,这将只留下您想要的线条。 然后处理这些行。

 /(?<=Start of numbers).*(?=End of numbers)/s 

您需要启用dotall标志。

http://regexr.com?30oaj