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
Regex.Matchesfinds all matches, not just the first.- The collection enumerates, so
Selectmaps captures to ints. MaxandSumfinish the job the regex started.
Keywords and builtins used here
intstringusingvar
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.
Step 3 of 3 in Regular expressions, step 3 of 17 in The .NET library.