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(e开发者_如何学运维xpression, "??");
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
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
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.
This one should get what you need:
\(((?>\((?<DEPTH>)|\)(?<-DEPTH>)|.?)*(?(DEPTH)(?!)))\)
Check this article for an overview of "nested constructions": http://www.codeproject.com/KB/recipes/Nested_RegEx_explained.aspx
Try with regex:
([^*]+\*)\s*\x28(.+?)\x29\s+([^-]+\-)(.+?)
-
string a = "3 + 2 * ((1 + 1 - (2 + 4))) + 112 * 31 - ((1+1) - 14 + 1)";
Match match = Regex.Match(a, @"([^*]+\*)\s*\x28(.+?)\x29\s+([^-]+\-)(.+?)");
for (int c = 0, len = match.Length; c < len; c++)
{
Console.WriteLine(match.Groups[c].Value);
}
Well,I have no any better idea of as parsing this.
精彩评论