fork download
  1. using System;
  2. using System.Linq;
  3. using System.Collections.Generic;
  4. using System.Text.RegularExpressions;
  5.  
  6. public class Test
  7. {
  8. private static readonly Dictionary<string, string> Pieces = new Dictionary<string, string>
  9. {
  10. { "month", @"(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)" },
  11. { "day", @"\d+" },
  12. { "hour", @"\d+" },
  13. { "the_rest", @".*" },
  14. };
  15.  
  16. public static void Main()
  17. {
  18. var str = "JAN 01 00:00:01 <Admin> Action, May have spaces etc.";
  19. var format = "{month} {day} {hour}:{the_rest}";
  20.  
  21. var results = Parse(str, format);
  22. if (results == null) {
  23. Console.WriteLine("Regex did not match");
  24. return;
  25. }
  26.  
  27. foreach(var name in Pieces.Keys) {
  28. Console.WriteLine(string.Format("{0} = {1}", name, results[name]));
  29. }
  30. }
  31.  
  32. public static IDictionary<string, string> Parse(string input, string format)
  33. {
  34. var re = Regex.Replace(format,
  35. @"\{(\w+)\}",
  36. m => string.Format("(?<{0}>{1})", m.Groups[1].Value, Pieces[m.Groups[1].Value]));
  37. var regex = new Regex("^" + re + "$", RegexOptions.ExplicitCapture);
  38. var match = regex.Match(input);
  39. return match.Success
  40. ? regex.GetGroupNames().ToDictionary(n => n, n => match.Groups[n].Value)
  41. : null;
  42. }
  43. }
Success #stdin #stdout 0.09s 37496KB
stdin
Standard input is empty
stdout
month = JAN
day = 01
hour = 00
the_rest = 00:01 <Admin> Action, May have spaces etc.