kotunec

QueryMess / Regex / Softuni

Feb 23rd, 2017
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.65 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Text.RegularExpressions;
  5.  
  6. class QueryMess
  7. {
  8.     static void Main()
  9.     {
  10.         // regex patterns
  11.         string pattern = @"([^&=?]*)=([^&=]*)";
  12.         string regex = @"((%20|\+)+)";
  13.  
  14.         // input and matching
  15.         string inputLine;
  16.  
  17.         while (!((inputLine = Console.ReadLine()) == "END"))
  18.         {
  19.             Regex pairs = new Regex(pattern);
  20.             MatchCollection matches = pairs.Matches(inputLine);
  21.  
  22.             // storing matching fields and values into a dictionary, per line of input
  23.             Dictionary<string, List<string>> results = new Dictionary<string, List<string>>();
  24.             for (int i = 0; i < matches.Count; i++)
  25.             {
  26.                 string field = matches[i].Groups[1].Value;
  27.                 field = Regex.Replace(field, regex, word => " ").Trim();
  28.  
  29.                 string value = matches[i].Groups[2].Value;
  30.                 value = Regex.Replace(value, regex, word => " ").Trim();
  31.  
  32.                 if (!results.ContainsKey(field))
  33.                 {
  34.                     List<string> values = new List<string>();
  35.                     values.Add(value);
  36.                     results.Add(field, values);
  37.                 }
  38.                 else if (results.ContainsKey(field))
  39.                 {
  40.                     results[field].Add(value);
  41.                 }
  42.             }
  43.  
  44.             // printing
  45.             foreach (var pair in results)
  46.             {
  47.                 Console.Write("{0}=[{1}]", pair.Key, string.Join(", ", pair.Value));
  48.             }
  49.             Console.WriteLine();
  50.         }
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment