Пример #1
0
 static string SeperateAndSimplify(string input)
 {
     if (input.Contains("("))
     {
         //we still have parenthesis - this regex will find multiple matches but we only need deal with the first because reciprocity
         Regex rgx = new Regex(@"\((?>\((?<c>)|[^()]+|\)(?<-c>))*(?(c)(?!))\)", RegexOptions.Compiled);
         Match m = rgx.Match(input);
         if (m.Success)
         {
             var sc = new SubCalc() { StartPos = m.Index, EndPos = (m.Index + m.Length), SubCalcText = m.Value.Substring(1, m.Value.Length - 2) };
             if (sc.SubCalcText.Contains("("))
             {
                 //we have a nest, process again
                 sc.SubCalcText =  SeperateAndSimplify(sc.SubCalcText);
                 input = Rebuild(input, sc);
             }
             else
             {
                 input = Rebuild(input, sc);
             }
         }
     }
     //we check again to contend with nesting..
     if (input.Contains("("))
     {
         input = SeperateAndSimplify(input);
     }
     return input;
 }
 static string SeperateAndSimplify(string input)
 {
     if (input.Contains("("))
     {
         //we still have parenthesis
         Regex rgx = new Regex(@"\((?>\((?<c>)|[^()]+|\)(?<-c>))*(?(c)(?!))\)", RegexOptions.Compiled);
         Match m   = rgx.Match(input);
         if (m.Success)
         {
             var sc = new SubCalc()
             {
                 StartPos = m.Index, EndPos = (m.Index + m.Length), SubCalcText = m.Value.Substring(1, m.Value.Length - 2)
             };
             if (sc.SubCalcText.Contains("("))
             {
                 //we have a nest, process again
                 sc.SubCalcText = SeperateAndSimplify(sc.SubCalcText);
                 input          = Rebuild(input, sc);
             }
             else
             {
                 input = Rebuild(input, sc);
             }
         }
     }
     if (input.Contains("("))
     {
         input = SeperateAndSimplify(input);
     }
     return(input);
 }
Пример #3
0
 public static string Simplify(string input)
 {
     CalcText = input;
     while (CalcText.Contains("("))
     {
         GetPositions();
         var _l = LPosList.OrderByDescending(x => x).ElementAt(0);
         var _r = RPosList.OrderBy(x => x).ElementAt(0);
         var sc = new SubCalc()
         {
             StartPos = _l, EndPos = _r, SubCalcText = CalcText.Substring(_l + 1, ((_r - _l) - 1))
         };
         CalcText = CalcText.Substring(0, sc.StartPos) + sc.Result + CalcText.Substring(sc.EndPos + 1, (CalcText.Length - 1) - sc.EndPos);
     }
     return(CalcText);
 }
 static string Rebuild(string input, SubCalc sc)
 {
     return(input.Substring(0, sc.StartPos) + sc.Result + input.Substring(sc.EndPos));
 }