Match & groups in C#
Named groups turn a log line into fields.
using System.Text.RegularExpressions;
var log = "GET /api/users 200 in 45ms";
var pattern = new Regex(@"(?<verb>GET|POST) (?<path>\S+) (?<code>\d{3})");
var m = pattern.Match(log);
if (m.Success)
{
Console.WriteLine($"verb: {m.Groups["verb"].Value}");
Console.WriteLine($"path: {m.Groups["path"].Value}");
Console.WriteLine($"code: {m.Groups["code"].Value}");
}
How it works
- The
(?<name>...)syntax names what the pattern captures. Matchfinds the first occurrence;Successgates the reads.m.Groups["path"]reads a capture by name, not position.
Keywords and builtins used here
ifnewusingvar
The run, in numbers
- Lines
- 12
- Characters to type
- 363
- Tokens
- 62
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 46 seconds.
Step 1 of 3 in Regular expressions, step 1 of 17 in The .NET library.