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, andundefined. - Never mutates input.
- Never throws.
- Always returns a structured
ParseResultwith 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
RegExpcompilation. - Invalid patterns are caught safely using a
try/catcharound theRegExpconstructor. - Suitable for normalization before validation or domain logic that requires a guaranteed-valid
RegExpinstance. - The parser is pure, deterministic, and side-effect-free.