PostgreSQL regexp_like: A Practical How-To
In this article
PostgreSQL does not have a built-in regexp_like function. To check whether a string matches a regular expression, use the ~ operator (case-sensitive) or ~* (case-insensitive), or the regexp_match() function when you need the matched text. The ~ operator returns a boolean and is the direct equivalent of Oracle's REGEXP_LIKE. This guide shows how to use it, how to write patterns safely, and what to do when results surprise you.
What You'll Need
- A PostgreSQL database (version 9.0 or later; the
~operator has existed for much longer, but modern versions are recommended). - A client to run SQL:
psql, pgAdmin, DBeaver, or any tool that connects to PostgreSQL. - Basic familiarity with SQL
SELECTandWHEREclauses. - Optional: a table with text data to test against. You can also test with literal strings, as shown below.
Step-by-Step
- Confirm your PostgreSQL version. Run
SELECT version();in your SQL client. The~operator works in all supported versions, but knowing your version helps when reading documentation. Menu labels in GUI clients can differ slightly by version, device, or region. - Test a basic match with the
~operator. Execute:SELECT 'hello world' ~ 'world';
This returnstrue. The left side is the string, the right side is the regular expression. The operator returns a boolean, exactly likeregexp_likein other databases. - Use case-insensitive matching with
~*. Run:SELECT 'Hello World' ~* 'hello';
This returnstrue. Use~when case matters and~*when it does not. - Anchor your pattern when you need an exact match. The pattern
'cat'matches any string containing "cat", including "concatenate". To match only the whole string, use^and$:SELECT 'cat' ~ '^cat$';
This returnstrue, whileSELECT 'concatenate' ~ '^cat$';returnsfalse. - Apply it in a
WHEREclause. Assuming a tableuserswith a columnemail, run:SELECT * FROM users WHERE email ~ '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$';
This filters rows whose email matches the pattern. Note the double backslash before the dot: in a standard SQL string, a single backslash is an escape character, so you write\\.to pass a literal\.to the regex engine. Alternatively, use a dollar-quoted string:$regex$\.[a-z]{2,}$regex$. - Use
regexp_match()when you need the matched text. The operator only tells you true or false. To extract the match, run:SELECT regexp_match('order 12345', '\d+');
This returns an array like{12345}. If there is no match, it returnsNULL. - Use
regexp_replace()for substitution. To replace matched text, run:SELECT regexp_replace('abc123', '\d+', '#');
This returnsabc#. This is useful for cleaning data before matching. - Test with
EXPLAINon large tables. Regex conditions are not indexable by default. If performance matters, consider a trigram index (pg_trgm extension) or a functional index on a simplified expression. RunEXPLAIN SELECT ...to see whether PostgreSQL uses a sequential scan. - Handle NULLs explicitly. If the column is NULL,
NULL ~ 'pattern'returnsNULL, notfalse. In aWHEREclause, NULL rows are excluded, which is usually what you want, but be aware when counting or usingNOT.
Common Mistakes
- Expecting a
regexp_likefunction. PostgreSQL does not provide one. Use~or~*. If you are porting SQL from Oracle, replaceREGEXP_LIKE(col, pat)withcol ~ pat. - Forgetting to escape backslashes. In standard SQL strings,
\dbecomesdunless you write\\d. Use dollar-quoted strings ($regex$...$regex$) to avoid double escaping. - Assuming
~is anchored. It matches anywhere in the string. Add^and$for full-string matching. - Using
LIKEwildcards inside a regex. In regex,%and_are literal characters, not wildcards. Use.*and.instead. - Ignoring case sensitivity.
~is case-sensitive;~*is not. Pick deliberately. - Assuming regex uses indexes. Plain
~conditions usually force a sequential scan. Plan for performance on large tables.
Tips
- Use
SIMILAR TOonly if you need SQL-standard pattern matching; for real regular expressions, stick with~. - Test patterns interactively with
SELECT 'sample' ~ 'pattern';before putting them in a query. - Prefer
regexp_match()oversubstring()when you need the matched substring; it is clearer and returns an array. - Use the
pg_trgmextension and a GIN or GiST index if you need faster pattern searches on large text columns. - Keep patterns simple. Complex regexes are hard to read and can be slow; break them into smaller checks where possible.
- Remember that PostgreSQL regexes are POSIX-style, not PCRE. Some PCRE features (like lookbehind) are not supported.
Troubleshooting
- Query returns no rows unexpectedly. Check case sensitivity: try
~*instead of~. Check anchoring: add^and$if you meant an exact match. Check escaping: print the pattern withSELECT 'pattern';to see what the database actually receives. - Syntax error near
~. Ensure the operator is between two string expressions, not used as a function call. For example,regexp_like(col, 'x')is invalid; usecol ~ 'x'. - Pattern works in another tool but not in PostgreSQL. PostgreSQL uses POSIX regular expressions. Features like
\p{L}or lookahead may not be supported. Simplify the pattern or useregexp_replace()in steps. - Performance is slow. Run
EXPLAIN ANALYZEto confirm a sequential scan. Consider a trigram index or rewriting the condition to useLIKEwith a prefix if possible. - NULL results confuse you. Remember that
NULL ~ 'x'isNULL. UseCOALESCE(col, '') ~ 'x'if you want NULL treated as an empty string. - If that did not work, check the PostgreSQL documentation for your version's regular expression syntax, and test the pattern against a literal string first to isolate whether the issue is the pattern or the data.
Frequently Asked Questions
Is there a regexp_like function in PostgreSQL?
No. PostgreSQL uses the ~ and ~* operators for boolean regex matching. There is no built-in function named regexp_like.
How do I do a case-insensitive regex match?
Use the ~* operator, for example SELECT 'Hello' ~* 'hello'; returns true. The ~ operator is case-sensitive.
Can I use regex in a WHERE clause?
Yes. Write WHERE column ~ 'pattern'. This filters rows where the pattern matches anywhere in the column value. Add anchors for exact matches.
How do I extract the matched text instead of just true/false?
Use regexp_match(), which returns an array of captured groups, or substring() with a regex pattern. For example, SELECT regexp_match('abc123', '\d+'); returns {123}.
Why does my pattern with backslashes fail?
In standard SQL strings, backslashes are escape characters. Double them (\\d) or use dollar-quoted strings ($regex$\d$regex$) to pass a single backslash to the regex engine.
Does ~ use indexes?
Not directly. Regex conditions typically cause a sequential scan. For large tables, consider a trigram index using the pg_trgm extension or a functional index on a simplified expression.