Regex .NET attached named group

风流意气都作罢 提交于 2019-12-11 06:07:34

问题


I want to get attached named group.

Source text:

1/2/3/4/5|id1:value1|id2:value2|id3:value3|1/4/2/7/7|id11:value11|id12:value12|

Group1:
1/2/3/4/5|id1:value1|id2:value2|id3:value3|
Sub groups:
id1:value1|
id2:value2|
id3:value3|

Group2:
1/4/2/7/7|id11:value11|id12:value12|
Sub groups:
id11:value11|
id12:value12|

How I can do this?


回答1:


While this task is easy enough without the complication by splitting, .Net regex matches hold a record of all captures of every group (unlike any other flavor that I know of), using the Group.Captures collection.

Match:

string pattern = @"(?<Header>\d(?:/\d)*\|)(?<Pair>\w+:\w+\|)+";
MatchCollection matches = Regex.Matches(str, pattern);

Use:

foreach (Match match in matches)
{
    Console.WriteLine(match.Value); // whole match ("Group1/2" in the question)
    Console.WriteLine(match.Groups["Header"].Value);
    foreach (Capture pair in match.Groups["Pair"].Captures)
    {
        Console.WriteLine(pair.Value); // "Sub groups" in the question
    }
}

Working example: http://ideone.com/5kbIQ



来源:https://stackoverflow.com/questions/5922683/regex-net-attached-named-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!