typestar

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

  1. The (?<name>...) syntax names what the pattern captures.
  2. Match finds the first occurrence; Success gates the reads.
  3. m.Groups["path"] reads a capture by name, not position.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Regular expressions, step 1 of 17 in The .NET library.

Next →