Q:

Regular Expression pattern to match a math expression

I have the following expression:
"3 + 2 * ((1 + 1 - (2 + 4))) + 112 * 31 - ((1+1) - 14 + 1)"

I want to split the expression with the top level parentesis
For example:
String Expression = "3 + 2 * ((1 + 1 - (2 + 4))) + 112 * 31 - ((1+1) - 14 + 1)";
String[] result = Regex.Split(expression, "??");

Expected output:
//result[0] = 3 + 2 *
//result[1] = (1 + 1 - (2 + 4))
//result[2] = + 112 * 31 -
//result[3] = 3 + 2 *
//result[4] = (1+1) - 14 + 1

A:

This isn't normally a job for regular expressions.  However, this msdn blog article suggests that it may be possible in the .net version using an extension called "Balanced Matching".
Not being a c# developer, I don't think I can finish answering, but perhaps this will help.
You might be better off finding or writing an actual parser though.

A:

This regex does what you want since you are using .NET. It uses a feature unique to .NET called balancing groups. 
^[^(]*(?=\()|(?<=\()(?>[^()]+|\((?<depth>)|\)(?<-depth>))*(?(depth)(?!))(?=\))|(?(depth)|[^\(\)]+)

The following code:
string expression = "3 + 2 * ((1 + 1 - (2 + 4))) + 112 * 31 - ((1+1) - 14 + 1)";
string pattern = @"^[^(]*(?=\()|(?<=\()(?>[^()]+|\((?<depth>)|\)(?<-depth>))*(?(depth)(?!))(?=\))|(?(depth)|[^\(\)]+)";
MatchCollection results = Regex.Matches(expression,pattern);

Results in the following values populating the results array:
//results[0] = 3 + 2 * 
//results[1] = (1 + 1 - (2 + 4))
//results[2] =  + 112 * 31 - 
//results[3] = (1+1) - 14 + 1

Here is a relevant blog post about balancing groups: http://blog.stevenlevithan.com/archives/balancing-groups

