简体   繁体   中英

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

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 ac# 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 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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM