![](/img/trans.png)
[英]How to get behavior of Group.Captures (from RegEx in C#) in Java?
[英]Regex match multiple Group.Captures with multiline
我想通過 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>");
}
抱歉,多行字符串格式損壞
如果您不需要驗證有 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("=============================");
}
這是迄今為止首選的選項。
例子
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("============================="); }
例子
表達式\\r\\n((?>\\r\\n.+){5})(?!\\r\\n.)
匹配:
\\r\\n
一個 cr+lf,后跟\\r\\n.+
cr+lf 和至少 1 個字符的行。(?> ... ){5}
是重復前 5 次。 它是一個原子組(在這種情況下更有效),最后是量詞。(?!\\r\\n.)
后面沒有 cr+lf 和一個字符(即后面沒有另一行)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.