Skip to content

parseRegExp

Attempts to parse a value into a genuine RegExp instance. This parser accepts existing RegExp objects and strings that can be compiled into a valid regular expression. It rejects invalid patterns and all non-regex-like values.

It never throws and never mutates input. Use it when you need a normalized, guaranteed-valid RegExp before further validation or domain logic.

Signature

function parseRegExp(value: unknown): ParseResult<RegExp>

Parameters

Returns

  • ok: true, value: RegExp, issues: []: when the value is a RegExp instance or a valid regex pattern string.
  • ok: false, value: null, issues: string[]: When the value cannot be parsed into a RegExp.

Behavior

  • Uses isRegExp internally to detect genuine RegExp instances.
  • Accepts:
  • Valid RegExp objects (returned as-is).
  • Strings that can be compiled into a RegExp.
  • Rejects:
  • Invalid regex pattern strings (for example, "[").
  • Numbers, objects, arrays, booleans, null, and undefined.
  • Never mutates input.
  • Never throws.
  • Always returns a structured ParseResult with value and issues.

Examples

parseRegExp(/abc/)
// { ok: true, value: /abc/, issues: [] }

parseRegExp("abc")
// { ok: true, value: /abc/, issues: [] }

parseRegExp("[")
// { ok: false, value: null, issues: ["String \"[\" is not a valid regular expression pattern"] }

parseRegExp(123)
// { ok: false, value: null, issues: ["Value must be a RegExp or a valid regex pattern string"] }

Notes

  • This parser intentionally allows string to RegExp compilation.
  • Invalid patterns are caught safely using a try/catch around the RegExp constructor.
  • Suitable for normalization before validation or domain logic that requires a guaranteed-valid RegExp instance.
  • The parser is pure, deterministic, and side-effect-free.