{"record":{"id":"ea867e024de6089c","repo":"different-ai/openwork","slug":"string-method-received-the-string-json-string","errorCode":null,"errorMessage":"String.${method} received the string ${JSON.stringify(arg)}, which is not a valid regular expression pattern (${regexFailureReason(error)}). ${escapeRegexHint}","messagePattern":"String\\.(.+?) received the string (.+?), which is not a valid regular expression pattern \\((.+?)\\)\\. (.+?)","errorType":"exception","errorClass":"InterpreterRuntimeError","httpStatus":null,"severity":"error","filePath":"packages/codemode/src/stdlib/regexp.ts","lineNumber":27,"sourceCode":"  \"multiline\",\n  \"sticky\",\n  \"unicode\",\n  \"dotAll\",\n])\n\nexport const regexFailureReason = (error: unknown): string =>\n  (error instanceof Error ? error.message : String(error)).replace(/^Invalid regular expression:\\s*/i, \"\")\n\nexport const escapeRegexHint =\n  'To match special characters like ( ) [ ] { } + * ? . literally, escape them with a backslash (e.g. \"\\\\\\\\(\") or test for them with String.includes instead.'\n\nexport const toHostRegex = (arg: unknown, method: string, node: AstNode, extraFlags = \"\"): RegExp => {\n  if (arg instanceof SandboxRegExp) return arg.regex\n  if (typeof arg === \"string\") {\n    try {\n      return new RegExp(arg, extraFlags)\n    } catch (error) {\n      throw new InterpreterRuntimeError(\n        `String.${method} received the string ${JSON.stringify(arg)}, which is not a valid regular expression pattern (${regexFailureReason(error)}). ${escapeRegexHint}`,\n        node,\n      ).as(\"SyntaxError\")\n    }\n  }\n  throw new InterpreterRuntimeError(\n    `String.${method} expects a regular expression (a /pattern/flags literal or new RegExp(...)) or a string pattern, not ${arg === null ? \"null\" : typeof arg}.`,\n    node,\n  )\n}\n\nexport const matchToValue = (match: RegExpMatchArray): Array<unknown> => {\n  const result: Array<unknown> = Array.from(match, (group) => group)\n  if (match.index !== undefined) (result as Record<string, unknown> & Array<unknown>).index = match.index\n  if (match.groups) {\n    const groups: SafeObject = Object.create(null) as SafeObject\n    for (const [key, group] of Object.entries(match.groups)) {\n      if (!isBlockedMember(key)) groups[key] = group","sourceCodeStart":9,"sourceCodeEnd":45,"githubUrl":"https://github.com/different-ai/openwork/blob/2b7df46e8ae1517d64c896c7793d2d52ec845669/packages/codemode/src/stdlib/regexp.ts#L9-L45","documentation":"toHostRegex compiles string arguments into host RegExp for String methods like match/replace/split. When the pattern string fails to compile (invalid syntax such as unbalanced brackets or bad groups), the underlying SyntaxError is rethrown as this InterpreterRuntimeError — surfaced as a SyntaxError via .as() — including the original failure reason and a hint about escaping.","triggerScenarios":"String.match('['), String.replaceAll('a{2,1}', ...), patterns interpolated from user input like new RegExp('(' + userTag + ')') where userTag contains regex metacharacters, unescaped dots/brackets from data, or an empty/invalid group '()+' edge in dynamically built patterns.","commonSituations":"Building patterns from config values or user-supplied delimiters without escaping; log-parsing scripts where the delimiter contains regex specials like '(' or '['; LLM-generated code with hand-written regex typos.","solutions":["Escape dynamic input before embedding: use an escapeRegExp helper (replace /[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')","Validate the pattern compiles in a plain JS try/catch with new RegExp(pattern) before running the CodeMode script","Prefer literal strings with split/indexOf over regex when the pattern is data","Fix hand-written regex syntax (balanced brackets, valid quantifiers) — the message names the exact failure reason"],"exampleFix":"// before\nconst parts = text.match('(' + userDelimiter + ')')\n// after\nconst esc = userDelimiter.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\nconst parts = text.match('(' + esc + ')')","handlingStrategy":"try-catch","validationCode":"function isValidRegex(pattern: string): boolean {\n  try { new RegExp(pattern); return true } catch { return false }\n}\nif (!isValidRegex(pattern)) pattern = escapeRegExp(pattern)","typeGuard":null,"tryCatchPattern":"try {\n  return text.match(pattern)\n} catch (e) {\n  if (e instanceof InterpreterRuntimeError && e.message.includes('not a valid regular expression pattern')) {\n    return text.split(escapeRegExp(pattern))[0] // or literal fallback\n  }\n  throw e\n}","preventionTips":["Escape dynamic input with an escapeRegExp helper before embedding","Precompile/validate patterns with new RegExp(pattern) in a plain try/catch before scripting","Prefer string split/indexOf over regex when the pattern is data","Check the failure reason in the message — it names the exact syntax problem"],"tags":["codemode","regex","syntax-error","string"],"backgroundTag":"invalid-regex-pattern","analyzedSha":"2b7df46e8ae1517d64c896c7793d2d52ec845669","analyzedAt":"2026-09-01T07:59:23.713Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-08T10:18:20.063Z"}