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?

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Ivan
  • 173
  • 1
  • 4
  • 18
  • @Mike: .NET `=>` C# or VB.NET. – Matt Ball May 07 '11 at 17:12
  • Why not just split the string on `|` and look at the result in groups of 4? – jb. May 07 '11 at 17:31
  • 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? – Kobi May 07 '11 at 18:39
  • I use C#. But this is not in principle, important to get pattern, if this can be done in one pattern. – Ivan May 08 '11 at 02:30

1 Answers1

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

Kobi
  • 135,331
  • 41
  • 252
  • 292
  • Thanks, this is good. How i can use next pattern: (?
    \d(?:/\d)*\|)((?\w+):(?\w+)\|)+ ? To compare the Id and Value in C# code.
    – Ivan May 08 '11 at 03:10