簡體   English   中英

正則表達式模式以匹配數學表達式

[英]Regular Expression pattern to match a math expression

我有以下表達:

"3 + 2 * ((1 + 1 - (2 + 4))) + 112 * 31 - ((1+1) - 14 + 1)"

我想用頂級括號分割表達式

例如:

String Expression = "3 + 2 * ((1 + 1 - (2 + 4))) + 112 * 31 - ((1+1) - 14 + 1)";
String[] result = Regex.Split(expression, "??");

預期產量:

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

通常,這不是正則表達式的工作。 但是,此msdn博客文章建議在.net版本中使用名為“平衡匹配”的擴展名是可能的。

不是AC#開發人員,我認為我無法完成回答,但這也許會有所幫助。

不過,最好是找到或編寫一個實際的解析器。

由於您使用的是.NET,因此此正則表達式可以滿足您的要求。 它使用了.NET獨有的稱為平衡組的功能。

^[^(]*(?=\()|(?<=\()(?>[^()]+|\((?<depth>)|\)(?<-depth>))*(?(depth)(?!))(?=\))|(?(depth)|[^\(\)]+)

如下代碼:

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[0] = 3 + 2 * 
//results[1] = (1 + 1 - (2 + 4))
//results[2] =  + 112 * 31 - 
//results[3] = (1+1) - 14 + 1

這是有關平衡組的相關博客文章: http : //blog.stevenlevithan.com/archives/balancing-groups

嘗試使用正則表達式:

([^*]+\*)\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);
                }

好吧,我對此沒有更好的主意。

這應該可以滿足您的需求:

\(((?>\((?<DEPTH>)|\)(?<-DEPTH>)|.?)*(?(DEPTH)(?!)))\)

檢查本文以獲得“嵌套結構”的概述: http : //www.codeproject.com/KB/recipes/Nested_RegEx_explained.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM