Regex Problem:How to use "balancing group definition"?

  • Thread starter Thread starter Guest
  • Start date Start date
Fire,
The following example is taken directly from the e-book "Regular
Expressions with .NET" By Dan Appleman. It only cost $14.95 and is available
for download as soon as you pay. It's a very good resource to have.
Jared

using System;
using System.Text.RegularExpressions;

class AdvancedTests
{
[STAThread]
static void Main(string[] args)
{
AdvancedTests.CommaMatching();
Console.ReadLine();
}

public static void CommaMatching()
{
string inputstring = "1 + ((5 + 3)+ 8 + (4 + (7))) + 6";
MatchCollection parenmatches;
Regex rxparens = new Regex(inputstring);
// First find the locations of left parens
parenmatches = Regex.Matches(inputstring, @"\(");

//Regex rx = new Regex(@"\(.*\)");
//Regex rx = new
Regex(@"(?:(?<ltparen>\()|(?<rtparen-ltparen>\))|[^\)\(])*");
Regex rx = new
Regex(@"(?:(?<ltparen>\()|(?<rtparen-ltparen>\))|(?(ltparen)[^\(\)]*|.*))*");

Match m;
GroupCollection gps;
foreach(Match parenmatch in parenmatches)
{
// Perform the match for each left paren found
m = rx.Match(inputstring, parenmatch.Index);
if (m.Success)
{
gps = m.Groups;
Console.WriteLine(m.Value);
int x;
int[] groupnums = rx.GetGroupNumbers();
String[] groupnames = rx.GetGroupNames();
for(x = 0;x<= groupnums.Length - 1;x++)
{
Console.WriteLine(" Group #: " + groupnums[x].ToString() + " name: "
+ groupnames[x] + " value = " + gps[x].Value);
}
}

}

}

}
 
Back
Top