Share Pastebin
Guest
Public paste!

Untitled

By: a guest | Aug 28th, 2008 | Syntax: C# | Size: 1.14 KB | Hits: 460 | Expires: Never
Copy text to clipboard
  1. using System;
  2. using System.Text.RegularExpressions;
  3. namespace myapp
  4. {
  5.     class Class1
  6.     {
  7.         static void Main(string[] args)
  8.         {
  9.             String sourcestring = @"[[Text:hi this is a nice sentence[[very nice]] I like this text]] this is not related [[not]]";
  10.             Regex re = new Regex(@"\[(?>[^\[\]]+|\[(?<DEPTH>)|\](?<-DEPTH>))*(?(DEPTH)(?!))\]");
  11.             MatchCollection mc = re.Matches(sourcestring);
  12.  
  13.             // to iterate through the matches and catpure groups
  14.             int mIdx = 0;
  15.             foreach (Match m in mc)
  16.             {
  17.                 for (int gIdx = 0; gIdx < m.Groups.Count; gIdx++)
  18.                 {
  19.                     Console.WriteLine("[" + mIdx + "][" + re.GetGroupNames()[gIdx] + "] = " + m.Groups[gIdx].Value);
  20.                 }
  21.                 mIdx++;
  22.             }
  23.  
  24.             //  to iterate through the [[Text:... matches only
  25.             foreach (Match m in mc)
  26.             {
  27.                 if (m.Groups[0].Value.Substring(0, 7) == "[[Text:")
  28.                 {
  29.                     Console.WriteLine(m.Groups[0].Value);
  30.                 }
  31.             }
  32.         }
  33.     }
  34. }