Skip to content

Instantly share code, notes, and snippets.

@jimmcslim
Created October 28, 2015 07:11
Show Gist options
  • Save jimmcslim/4c1b45e1f5a61888d8ec to your computer and use it in GitHub Desktop.
Save jimmcslim/4c1b45e1f5a61888d8ec to your computer and use it in GitHub Desktop.
Bare-bones Grok implementation in C#, translated from http://stackoverflow.com/a/23078970/28381
var Types = new Dictionary<string, string>
{
{"WORD", @"\w+"},
{"NUMBER", @"\d+"},
};
var grok = new Regex(@"%{(\w+):(\w+)}");
MatchEvaluator e = match => string.Format("(?<{0}>{1})", match.Groups[2].Value, Types[match.Groups[1].Value]);
var regex = new Regex(grok.Replace("%{WORD:method} %{NUMBER:bytes} %{NUMBER:duration}", e));
var matchCollection = regex.Match("hello 123 456");
Console.WriteLine("Method: {0} Bytes: {1}, Duration: {2}",
matchCollection.Groups["method"].Value,
matchCollection.Groups["bytes"].Value,
matchCollection.Groups["duration"].Value);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment