关于带括号类函数或公式的提取问题

在进行表达式分析时,我们会遇到类似这样的语句:b*Avg(a*3,b/6,c+8,e+f*(-(g/(h-i)))*j) ,经过分析,Avg(...)里,括号内有以逗号分隔的多个表达式,则涉及到括号配对的问题。

这里利用正则表达式的平衡组方式解决括号内容提取问题。

经提取解析后,生成类似表达式:b*(a*3 + b/6 + c+8 + e+f*(-(g/(h-i)))*j) * 1d /4 /9 + ……

即自动将Avg()中的字符连加,再除以项目数。当然,本示例还有一些可优化之处,比如:/4 /9 可以优化成为:/36等,现实中,根据具体需求优化之。


        public string ParseAvg(string expr)
        {
            //expr = "b*Avg(a*3,b/6,c+8,e+f*(-(g/(h-i)))*j) /9+ Avg(4*a*3,(8+b)/6,c*8) + 99 * sum(a,b,c,d)";
            string patternCore = @"Avg\s*\(((?<cores>\()|(?<-cores>\))|.)*?(?(cores)(?!))\)";
            List<string> listMatch = new List<string>();
            List<string> listNewValue = new List<string>();
            foreach (Match m in Regex.Matches(expr, patternCore, RegexOptions.IgnoreCase | RegexOptions.Multiline))
            {
                string oldValue = m.Value;
                int len = oldValue.Split(',').Length;
                string newValue = oldValue.Replace(',', '+') + "*1d / " + len.ToString();
                newValue = Regex.Replace(newValue, "avg", "", RegexOptions.IgnoreCase);
                listNewValue.Add(newValue);
                listMatch.Add(oldValue);
            }


            for (int i = 0; i < listNewValue.Count(); i++)
            {
                expr = expr.Replace(listMatch[i], listNewValue[i]);
            }


            return expr;
        }

猜你喜欢

转载自blog.csdn.net/johnsuna/article/details/70228229