invalid regular expression
SQLSTATE 2201B is raised when a regular expression pattern passed to ~ (regex match), regexp_match, regexp_replace, or similar functions is syntactically invalid and cannot be compiled.
- 1A malformed regular expression with unclosed parentheses, invalid quantifiers, or other syntax errors
- 2Using PCRE-only syntax (e.g., lookaheads) in Postgres which uses POSIX ERE
Regex match with a syntax error in the pattern.
SELECT 'hello' ~ '(unclosed';
expected output
ERROR: invalid regular expression: parentheses () not balanced
Fix 1
Fix the regex syntax error
WHEN When a hand-authored regex fails.
SELECT 'hello' ~ '(closed)';
Why this works
Ensure all parentheses, brackets, and quantifiers are correctly balanced and use POSIX ERE syntax supported by Postgres.
Fix 2
Test regex patterns before deploying
WHEN When patterns are dynamically built from user input.
-- Wrap in a BEGIN/EXCEPTION block to catch 2201B and return NULL: DO $ BEGIN PERFORM 'test' ~ :'user_pattern'; EXCEPTION WHEN invalid_regular_expression THEN RAISE NOTICE 'Bad pattern'; END $;
Why this works
Catching 2201B in PL/pgSQL lets you validate user-supplied patterns without crashing the query.
✕ Pass unsanitised user input as a regex pattern
An invalid pattern raises 2201B and aborts the query; a valid but complex pattern can cause catastrophic backtracking.
Class 22 — Data Exception
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev