Build a small regex golf game in a C# console: type a pattern, match ten target words, and avoid ten forbidden words. A winning round scores 10 targets and 0 forbidden matches. Once you win, try to shorten the pattern.
This tutorial targets a .NET 10 SDK console app and uses only the base class library. If console loops or exception handling are new to you, start with C# loops and exception handling.
The board and the scoring rule
| Targets | Forbidden |
|---|---|
| cat, car, cap, can, cab, bat, bar, bag, ban, BAD | cot, cop, cup, cut, cow, bit, bot, bug, bun, bed |
Each word contributes at most one point to its list, even if a pattern could match several places in that word. The program calls IsMatch once per word. It does not require the match to consume the whole word: anchors are your choice. Pattern length is the entered string’s Length, counting UTF-16 code units, including spaces and backslashes. The examples here use ASCII patterns.
Matching is case-insensitive deliberately, so the uppercase target BAD participates in the same puzzle. IgnoreCase normally follows the current culture; combining it with CultureInvariant selects invariant-culture casing rules. See Microsoft’s regular expression options. Patterns can still contain inline option switches, so treat this as a local experiment rather than a validation policy for outside input.
Create the app and check it before playing
With the .NET 10 SDK installed, create a console project:
dotnet new console --framework net10.0 --name RegexGolf
cd RegexGolf
Replace Program.cs with this complete program. Its default mode runs three stored patterns and asserts their outcomes. Add --play to run those checks and then enter the game.
using System;
using System.Text.RegularExpressions;
internal static class Program
{
private static readonly string[] Targets =
{ "cat", "car", "cap", "can", "cab", "bat", "bar", "bag", "ban", "BAD" };
private static readonly string[] Forbidden =
{ "cot", "cop", "cup", "cut", "cow", "bit", "bot", "bug", "bun", "bed" };
private static readonly TimeSpan MatchTimeout = TimeSpan.FromMilliseconds(100);
private static void Main(string[] args)
{
SelfCheck();
if (Array.IndexOf(args, "--play") < 0)
return;
Console.WriteLine("Targets: " + string.Join(", ", Targets));
Console.WriteLine("Forbidden: " + string.Join(", ", Forbidden));
Console.WriteLine("Match all 10 targets and no forbidden words. Type :quit to leave.");
int? best = null;
while (true)
{
Console.Write("Pattern> ");
string? pattern = Console.ReadLine();
if (pattern is null || pattern == ":quit")
break;
try
{
var score = Score(pattern);
best = UpdateBest(best, score.Targets, score.Forbidden, pattern.Length);
Console.WriteLine($"Targets {score.Targets}/10; forbidden {score.Forbidden}/10; length {pattern.Length}");
if (IsWin(score.Targets, score.Forbidden))
Console.WriteLine($"Win! Shortest winning length this session: {best}");
}
catch (ArgumentException)
{
Console.WriteLine($"Invalid pattern; length {pattern.Length}. Round not scored.");
}
catch (RegexMatchTimeoutException)
{
Console.WriteLine($"Match timed out; length {pattern.Length}. Round not scored.");
}
}
}
private static (int Targets, int Forbidden) Score(string pattern)
{
var regex = new Regex(pattern,
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, MatchTimeout);
int targets = 0;
int forbidden = 0;
foreach (string word in Targets)
if (regex.IsMatch(word))
targets++;
foreach (string word in Forbidden)
if (regex.IsMatch(word))
forbidden++;
return (targets, forbidden);
}
private static bool IsWin(int targets, int forbidden) => targets == 10 && forbidden == 0;
private static int? UpdateBest(int? best, int targets, int forbidden, int length)
{
if (IsWin(targets, forbidden) && (best is null || length < best.Value))
return length;
return best;
}
private static void SelfCheck()
{
var cases = new (string Pattern, bool Invalid, int Targets, int Forbidden)[]
{
("[", true, 0, 0),
("^c", false, 5, 5),
("^[cb]a", false, 10, 0)
};
int? best = null;
foreach (var test in cases)
{
try
{
var score = Score(test.Pattern);
Require(!test.Invalid && score.Targets == test.Targets &&
score.Forbidden == test.Forbidden, "Unexpected score");
best = UpdateBest(best, score.Targets, score.Forbidden, test.Pattern.Length);
Console.WriteLine($"PASS {test.Pattern}: targets={score.Targets}, forbidden={score.Forbidden}, length={test.Pattern.Length}");
}
catch (ArgumentException error)
{
Require(test.Invalid && error is RegexParseException, "Unexpected parse failure");
Console.WriteLine($"PASS {test.Pattern}: invalid RegexParseException, length={test.Pattern.Length}");
}
}
Require(best == 6, "Winning length was not recorded");
Require(UpdateBest(best, 9, 0, 1) == 6, "Partial match changed best");
Require(UpdateBest(best, 10, 1, 1) == 6, "Forbidden match changed best");
Require(UpdateBest(best, 10, 0, 8) == 6, "Longer win changed best");
Require(UpdateBest(best, 10, 0, 5) == 5, "Shorter win did not change best");
Console.WriteLine("PASS session best: only a shorter 10/0 win replaces it");
}
private static void Require(bool condition, string message)
{
if (!condition)
throw new InvalidOperationException(message);
}
}
Run the self-check:
dotnet run
The program’s expected output is:
PASS [: invalid RegexParseException, length=1
PASS ^c: targets=5, forbidden=5, length=2
PASS ^[cb]a: targets=10, forbidden=0, length=6
PASS session best: only a shorter 10/0 win replaces it
The example was built and run in an offline .NET 10 SDK container; the build reported zero warnings and zero errors, and stdout matched these four lines exactly. A second container fixture fed the play loop invalid, partial, empty, and winning patterns. It checked that the session best changed from seven to six and stayed six after a longer win. The self-check also exercises the best-score helper with synthetic scores, including a shorter win. It does not deliberately trigger a matching timeout.
Play a round: anchors, alternatives, and a character class
Start interactive play:
dotnet run -- --play
After the four PASS lines, the game prints the lists and prompts for a pattern. Enter each pattern on its own line, without C# quotes or surrounding slashes. Type :quit, or send end-of-input, to leave. No score is saved between runs.
-
Enter
^c. The start anchor restricts the match to words beginning with c. This scores 5 targets and 5 forbidden words: a useful partial result, but not a win. -
Enter
^ca|^ba. The vertical bar offers alternatives: a ca prefix or a ba prefix. Both branches have their own start anchor. This seven-character pattern scores 10/0 and sets the session best to seven. -
Enter
^[cb]a. The character class selects one character, c or b, followed by a. It scores 10/0 with six characters, so the session best becomes six.
These constructs are defined in Microsoft’s regex language quick reference. The winning patterns match prefixes rather than whole words. If you want whole-string matching in a different puzzle, \A and \z assert the absolute start and end. The familiar $ can also match before a final newline; it is not identical to \z.
The empty pattern is legal and matches every word here, giving 10/10 with length zero. That demonstrates why a short pattern alone is insufficient. Likewise, an invalid pattern is not a zero-match score: the round is rejected and the previous best survives.
Keep mistakes inside the round
The three-argument Regex constructor accepts the pattern, options, and matching timeout. A parsing error is caught through ArgumentException; in the tested .NET 10 case, the actual exception is RegexParseException, which the self-check verifies through that catch. The failed assertion helper throws a different exception, so a bad expected result cannot masquerade as a successful parse-error test.
The 100-millisecond setting applies to each matching operation. It is not a strict stopwatch bound on constructing a regex or completing all twenty checks. If matching throws RegexMatchTimeoutException, the game abandons that round without updating the best. The constructor documentation explains the timeout behavior; these tiny fixed words do not establish a worst-case time limit for arbitrary patterns.
Try to beat six characters on this board. You can exploit any shared feature of the target words that the forbidden list lacks; an anchor is a tool, not a requirement. Once you understand why a shorter pattern wins, change the two lists and update the three expected cases before playing again.