iOfficeAI/OfficeCLI · error · ArgumentException

Invalid regex pattern '{pattern}': {ex.Message}

Error message

Invalid regex pattern '{pattern}': {ex.Message}

What it means

Thrown by FindHelpers when a caller-supplied regex pattern fails to parse (RegexParseException). The match is run with a hard timeout to defend against catastrophic backtracking; a structurally invalid pattern is caught and rewrapped as an ArgumentException that names the pattern and the parser's message.

Source

Thrown at src/officecli/Core/FindHelpers.cs:60

    /// </summary>
    internal static List<(int Start, int Length)> FindMatchRanges(string fullText, string pattern, bool isRegex)
    {
        var ranges = new List<(int Start, int Length)>();
        if (isRegex)
        {
            try
            {
                // Bound matching with a hard timeout so catastrophic-backtracking
                // patterns (e.g. "(a+)+b") fail fast instead of hanging the process.
                foreach (Match m in Regex.Matches(fullText, pattern, RegexOptions.None, RegexMatchTimeout))
                {
                    if (m.Length > 0) // skip zero-length matches
                        ranges.Add((m.Index, m.Length));
                }
            }
            catch (RegexParseException ex)
            {
                throw new ArgumentException($"Invalid regex pattern '{pattern}': {ex.Message}", ex);
            }
            catch (RegexMatchTimeoutException ex)
            {
                throw new ArgumentException(
                    $"Regex pattern '{pattern}' exceeded {RegexMatchTimeout.TotalSeconds}s match timeout (catastrophic backtracking?)",
                    ex);
            }
        }
        else
        {
            int idx = 0;
            while ((idx = fullText.IndexOf(pattern, idx, StringComparison.Ordinal)) >= 0)
            {
                ranges.Add((idx, pattern.Length));
                idx += pattern.Length;
            }
        }
        return ranges;

View on GitHub (pinned to 1ced45e900)

Solutions

  1. Fix the pattern syntax (balance groups, escape metacharacters, valid ranges).
  2. Test the pattern with Regex() in isolation before passing it.
  3. If the pattern comes from user input, validate it with a try/new Regex(...) first and reject early.

Example fix

// before
Find(sheet, pattern: "(foo", useRegex: true); // unbalanced group
// after
Find(sheet, pattern: "(foo)", useRegex: true);
Defensive patterns

Strategy: try-catch

Validate before calling

static void ValidateRegex(string pattern)
{
    _ = new Regex(pattern, RegexOptions.None, FindHelpers.RegexMatchTimeout);
}

Type guard

static bool IsValidRegex(string pattern)
{ try { _ = new Regex(pattern); return true; } catch { return false; } }

Try / catch

try { Find(sheet, pattern, useRegex: true); }
catch (ArgumentException ex) when (ex.Message.Contains("Invalid regex pattern"))
{ /* report bad pattern to user */ }

Prevention

When it happens

Trigger: Calling a find/search API with regex enabled (e.g. a find/findAll option that treats the query as a regular expression) using a syntactically invalid pattern such as unbalanced parentheses, a dangling quantifier, or an invalid character class.

Common situations: User-typed regex with a typo ('(' unclosed, '*' at start, '[invalid range); regex built from unescaped dynamic input that injects metacharacters; a pattern valid in another regex flavor but not .NET.

Related errors


AI-assisted analysis of iOfficeAI/OfficeCLI@1ced45e900 (2026-08-13). Data as JSON: /api/errors/46c1a1a97748dca0. Report an issue: GitHub.