Skip to content

Regex Tester — C# source

Test regular expressions against any text with all flags (g/i/m/s/u/y). See every match, its index and capture groups, plus the constructed pattern. 100% in-browser.

This is the C# implementation — the same logic the interactive tool runs, in a shareable, citable form.

// regex-tester — C# port. Match a pattern against text, report every match
// with capture groups and index (System.Text.RegularExpressions).
using System;
using System.Collections.Generic;
using System.Linq;

record RegexMatch(string Match, int Index, List<string> Groups);

static class RegexTester
{
    // JS flag letters -> RegexOptions. g selects all matches; u is the
    // default for .NET strings; y has no equivalent.
    static RegexOptions CompileFlags(string flags) => flags.Aggregate(
        RegexOptions.None,
        (o, f) => f switch
        {
            'i' => o | RegexOptions.IgnoreCase,
            'm' => o | RegexOptions.Multiline,
            's' => o | RegexOptions.Singleline,
            _ => o,
        });

    static List<RegexMatch> RunRegex(string pattern, string flags, string text)
    {
        try
        {
            var re = new Regex(pattern, CompileFlags(flags));
            int limit = flags.Contains('g') ? 2000 : 1;
            var found = re.Matches(text);
            var outList = new List<RegexMatch>();
            for (int i = 0; i < found.Count && outList.Count < limit; i++)
            {
                var m = found[i];
                var groups = m.Groups.Cast<Group>().Skip(1)
                    .Select(g => g.Success ? g.Value : "").ToList();
                outList.Add(new RegexMatch(m.Value, m.Index, groups));
            }
            return outList;
        }
        catch (ArgumentException e)
        {
            Console.Error.WriteLine("error: " + e.Message);
            return new List<RegexMatch>();
        }
    }

    // Render a result the way the tool's UI does:
    // `N. "match" @ index -> [g1, g2]`, or `(none)` when empty.
    static string FormatMatches(List<RegexMatch> ms) =>
        ms.Count == 0 ? "(none)"
        : string.Join("\n", ms.Select((m, i) =>
            $"{i + 1}. \"{m.Match}\" @ {m.Index}" +
            (m.Groups.Count > 0 ? $" -> [{string.Join(", ", m.Groups)}]" : "")));

    static void Main()
    {
        var ms = RunRegex(@"(\w+)@(\w+)\.(\w+)", "g", "mail@x.com nope bob@test.org");
        Console.WriteLine(FormatMatches(ms));
    }
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →