Filkolev

Sum of All Values

May 27th, 2015
318
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Text.RegularExpressions;
  3.  
  4. public class SumOfAllValues
  5. {
  6.     public static void Main()
  7.     {
  8.         const string keysPattern = @"^(?<start>[a-zA-Z_]+)[0-9].*?[0-9](?<end>[a-zA-Z_]+)$";
  9.  
  10.         string keysString = Console.ReadLine();
  11.  
  12.         var match = Regex.Match(keysString, keysPattern);
  13.  
  14.         string start = match.Groups["start"].Value;
  15.         string end = match.Groups["end"].Value;
  16.  
  17.         if (start == string.Empty || end == string.Empty)
  18.         {
  19.             Console.WriteLine("<p>A key is missing</p>");
  20.             return;
  21.         }
  22.  
  23.         string text = Console.ReadLine();
  24.  
  25.         string numberPattern = string.Format("{0}(.*?){1}", start, end);
  26.  
  27.         var numbers = Regex.Matches(text, numberPattern);
  28.  
  29.         double sum = 0;
  30.  
  31.         foreach (Match numberMatch in numbers)
  32.         {
  33.             double number;
  34.             double.TryParse(numberMatch.Groups[1].Value, out number);
  35.  
  36.             sum += number;
  37.         }
  38.  
  39.         Console.WriteLine(
  40.             "<p>The total value is: <em>{0}</em></p>",
  41.             sum == 0 ? "nothing" : sum.ToString());
  42.     }
  43. }
RAW Paste Data