我希望在每次捕获之间获得5行+空行的所有捕获。 我正在尝试这种方式,但只收到第一次捕获。当我从测试字符串中删除第一个捕获时,我会收到下一个捕获,依此类推,所以看起来我的正则表达式是匹配的。 我错过了什么?
static void Main(string[] args)
{
var strBackups = @"wbadmin 1.0 - Backup command-line tool
(C) Copyright 2013 Microsoft Corporation. All rights reserved.
Backup time: 01.09.2015 11:51
Backup target: 1394/USB Disk labeled BIGGER2(F:)
Version identifier: 09/01/2015-06:51
Can recover: Volume(s), File(s), Application(s), Bare Metal Recovery, System State
Snapshot ID: {060e3b44-7b80-49bf-97c4-3f3b9908dec6}
Backup time: 06.09.2015 10:36
Backup target: 1394/USB Disk labeled BIGGER2(F:)
Version identifier: 09/06/2015-05:36
Can recover: Volume(s), File(s), Application(s), Bare Metal Recovery, System State
Snapshot ID: {64af3693-362d-42dc-ae5f-566b3f2d40be}
Backup time: 06.09.2015 11:00
Backup target: 1394/USB Disk labeled BIGGER2(F:)
Version identifier: 09/06/2015-06:00
Can recover: Volume(s), File(s), Application(s), Bare Metal Recovery, System State
Snapshot ID: {d9d50a01-6907-40a1-9c57-1f45de76b9ec}
";
var regBackups = new System.Text.RegularExpressions.Regex(".+\r\n.+\r\n\r\n(.+\r\n.+\r\n.+\r\n.+\r\n.+\r\n)+",
System.Text.RegularExpressions.RegexOptions.Compiled | System.Text.RegularExpressions.RegexOptions.Multiline
);
var match = regBackups.Match(strBackups);
if (match.Success)
{
for (var i = 1; i < match.Groups.Count; i++)
{
foreach (var c in match.Groups[i].Captures)
{
Console.WriteLine("=============================");
Console.WriteLine(c);
Console.WriteLine("=============================");
}
}
}
else
Console.WriteLine("<not matched>");
}
很抱歉多行字符串格式错误
答案 0 :(得分:0)
如果您不需要验证有5个连续的行,您可以简单地用空行拆分:
var regBackups = new System.Text.RegularExpressions.Regex("(?:\r\n){2}");
var result = regBackups.Split(strBackups);
foreach (var c in result)
{
Console.WriteLine("=============================");
Console.WriteLine(c);
Console.WriteLine("=============================");
}
这是目前为止的首选方案 Example
var regBackups = new Regex(@"\r\n((?>\r\n.+){5})(?!\r\n.)",
RegexOptions.Compiled
);
foreach (Match m in regBackups.Matches(strBackups))
{
Console.WriteLine("=============================");
Console.WriteLine(m.Groups[1].Value);
Console.WriteLine("=============================");
}
Example
表达式\r\n((?>\r\n.+){5})(?!\r\n.)
匹配:
\r\n
一个cr + lf,然后是\r\n.+
一个cr + lf和一行至少有一个字符。 (?> ... ){5}
将重复之前的5次。它是一个原子组(在这种情况下效率更高),最后有量词。(?!\r\n.)
后面没有cr + lf和一个字符(即没有后跟另一行)。