2011-06-18 34 views
2

我有以下表达式:正则表达式模式匹配一​​个数学表达式

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

我想与顶层parentesis

例如分割表达式:

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 
+7

你最好为此编写一个解析器(或者,最好的,只搜索一个 - 有一个好的已经在那里)。算术就像html - 不是_regular_。 –

+0

什么是“休闲表达”?它只是一个错字,或者这是某种符号? –

+0

我同意Joel的观点,但如果你真的想在正则表达式中做到这一点(如果你正在寻找一个挑战和/或你恨自己) - 你可能会对.NET的平衡模式匹配感兴趣。但正如Joel所说,Lexer/Parser是更好的选择。 – vcsjones

回答

3

这通常不是正则表达式的工作。但是,这个msdn blog article表明它可能在.net版本中使用名为“平衡匹配”的扩展名。

不是一个C#开发人员,我不认为我可以完成回答,但也许这会有所帮助。

虽然您可能会更好地查找或编写实际的解析器。

0

尝试用正则表达式:

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

好了,我的这个分析没有任何更好的主意。

3

此正则表达式你想要做什么,因为你使用的是.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