Regex .NET attached named group
Asked Answered
D

1

1

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?

Dezhnev answered 7/5, 2011 at 17:4 Comment(4)
@Mike: .NET => C# or VB.NET.Zola
Why not just split the string on | and look at the result in groups of 4?Nachison
I've added an answer that simply answers the question, but I suspect there's an easier solution, if you can add some details as to what you're doing. Another point: what do you mean by "Group" and "Sub Group"? Do you want a single Match object, with the Groups as you've described?Eb
I use C#. But this is not in principle, important to get pattern, if this can be done in one pattern.Dezhnev
E
0

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

Eb answered 7/5, 2011 at 18:36 Comment(1)
Thanks, this is good. How i can use next pattern: (?<Header>\d(?:/\d)*\|)((?<Id>\w+):(?<Value>\w+)\|)+ ? To compare the Id and Value in C# code.Dezhnev

© 2022 - 2024 — McMap. All rights reserved.