typestar

Matches & LINQ in C#

Every occurrence, straight into a LINQ pipeline.

using System.Text.RegularExpressions;

var doc = "Widths: 120px, 80px and 44px (min 12px).";

// Matches finds every occurrence; LINQ takes it from there
var sizes = Regex.Matches(doc, @"(\d+)px")
    .Select(m => int.Parse(m.Groups[1].Value))
    .ToList();

Console.WriteLine(string.Join(",", sizes));
Console.WriteLine($"max {sizes.Max()}, sum {sizes.Sum()}");

How it works

  1. Regex.Matches finds all matches, not just the first.
  2. The collection enumerates, so Select maps captures to ints.
  3. Max and Sum finish the job the regex started.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
355
Tokens
65
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 46 seconds.

Type this snippet

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

← Previous Next →