public static Summand Parse(string summandString) { if (summandString.IsNullOrWhiteSpace()) { throw new ArgumentNullException(nameof(summandString)); } if (!SummandRegex.IsMatch(summandString)) { throw new FormatException($"Could not parse summand string: {summandString}. Format string not matched by summand patters - '|(+,-)(number)|<variables=(name)^(power)>'."); } var regexGroupResult = SummandRegex.Match(summandString).Groups; var multiplierString = String.Empty; if (regexGroupResult[MultiplierRegexGroupName].Captures.Count == 1) { multiplierString = regexGroupResult[MultiplierRegexGroupName].Captures[0].Value; } if (multiplierString.Equals(String.Empty) || multiplierString.Equals(Symbols.Minus.ToString()) || multiplierString.Equals(Symbols.Plus.ToString())) { multiplierString += "1"; } var multiplier = float.Parse(multiplierString.Replace(',', '.'), NumberStyles.Any, CultureInfo.InvariantCulture.NumberFormat); if (Math.Abs(multiplier) < float.Epsilon) { return(new Summand(0)); } var variables = new List <Variable>(); foreach (Capture capture in regexGroupResult[VariblesRegexGroupName].Captures) { variables.Add(VariableParser.Parse(capture.Value)); } return(new Summand(variables, multiplier)); }
/// <summary> /// Parse a summand string e.g. 2x^2y^2 /// </summary> public static Summand Parse(string input) { var coefficientString = CoefficientRegex.Match(input).Value; var coefficient = String.IsNullOrEmpty(coefficientString) || coefficientString.Equals("+") ? 1 : coefficientString.Equals("-") ? -1 : float.Parse(coefficientString); var variables = VariablesRegex .Matches(input) .Select(i => VariableParser.Parse(i.Value)) .GroupBy(i => i.Name) .Select(i => new Variable(i.Key, i.Sum(j => j.Exponent))) .OrderBy(i => i.Name) .ToList(); var result = new Summand(coefficient, variables); return(result); }