Sub topic 12
Regular expressions: ~, regexp_replace and regexp_match
This chapter assumes you can write basic SELECT and WHERE queries, know how LIKE works, and can run queries in psql or another client. You don't need to have used regular expressions in another language. The chapter covers how PostgreSQL's regex operators and functions behave, and where they differ from what you may expect.
What a regular expression adds over LIKE
LIKE has two wildcards: % for any run of characters and _ for one character. A regular expression (regex) is a pattern language that can also express character classes, repetition, alternatives, groups and anchors. PostgreSQL uses the POSIX "advanced" regex flavor (ARE), which is close to Perl-style syntax.
Use LIKE when a simple wildcard is enough, because it is easier to read and easier to index. Use a regex when you need to validate a format, pull a piece out of text, or rewrite text by rule.
Matching with the ~ operators
Four operators test whether a string matches a pattern. Each returns a boolean.
| Operator | Meaning |
|---|---|
| `~` | Matches, case-sensitive |
| `~*` | Matches, case-insensitive |
| `!~` | Does not match, case-sensitive |
| `!~*` | Does not match, case-insensitive |
SELECT 'PostgreSQL' ~ 'sql' AS case_sensitive,
'PostgreSQL' ~* 'sql' AS case_insensitive,
'PostgreSQL' !~ 'MySQL' AS not_mysql,
'abc123' ~ '^[a-z]+\d+$' AS letters_then_digits;The result is f, t, t, t.
A regex match is not anchored. 'PostgreSQL' ~* 'sql' is true because the pattern matches anywhere in the string. LIKE is different: it must match the whole string. To require a whole-string match with a regex, anchor it with ^ (start) and $ (end).
SELECT '12a' ~ '\d+' AS found_digits,
'12a' ~ '^\d+$' AS only_digits;This returns t and f.
Syntax you will use most
| Element | Meaning | Column |
|---|---|---|
| `.` | Any single character | |
| `\d`, `\w`, `\s` | Digit, word character, whitespace | |
| `[abc]`, `[^abc]`, `[a-z]` | A set, a negated set, a range | |
| `*`, `+`, `?` | Zero or more, one or more, zero or one | |
| `{n}`, `{n,m}` | Exactly n, between n and m repetitions | |
| `(...)` | Capturing group | |
| `a\ | b` | Alternative |
| `^`, `$` | Start and end of string | |
| `\m`, `\M`, `\y` | Start of word, end of word, either |
A typical use is a format check on rows:
SELECT email,
email ~* '^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$' AS looks_valid
FROM (VALUES ('[email protected]'), ('bad@'), ('[email protected]')) AS t(email);This returns t, f, t. It is a sanity filter, not a full email validator.
Backslashes in string literals
With the default setting standard_conforming_strings = on, a backslash in an ordinary '...' literal is just a backslash. You write '\d+' and the regex engine sees \d+. If you use an escape string such as E'\\d+', you must double every backslash. Mixing the two styles is a common source of patterns that silently match nothing.
SELECT 'the cat sat' ~ '\ycat\y' AS standalone_word,
'concatenates' ~ '\ycat\y' AS inside_word;This returns t and f.
Rewriting text with regexp_replace
regexp_replace(source, pattern, replacement [, flags]) replaces matches of a pattern. The details that matter:
- By default it replaces only the first match. Add the
gflag to replace all matches. - In the replacement,
\1to\9insert the text captured by the numbered groups, and\&inserts the whole match. - If
sourceis NULL the result is NULL.
SELECT regexp_replace('a1b2c3', '\d', '#') AS first_only,
regexp_replace('a1b2c3', '\d', '#', 'g') AS all_matches,
regexp_replace('cat', 'cat', '[\&]') AS whole_match;The results are a#b2c3, a#b#c# and [cat].
Capture groups let you reorder pieces. This is the example from the topic plan:
SELECT regexp_replace('2026-11-27', '(\d+)-(\d+)-(\d+)', '\3/\2/\1') AS reordered;The result is 27/11/2026. Each group captures one number, and the replacement writes them in the opposite order.
A common cleanup is collapsing runs of whitespace:
SELECT trim(regexp_replace(' too many spaces ', '\s+', ' ', 'g')) AS cleaned;The result is too many spaces. Without trim, the leading and trailing runs would each become a single space.
Flags
The optional flags string combines letters. These are the useful ones:
| Flag | Effect |
|---|---|
| `g` | Replace or match all occurrences, not just the first |
| `i` | Case-insensitive |
| `c` | Case-sensitive (the default) |
| `n` | Newline-sensitive: `.` and negated sets do not match a newline, and `^` and `$` match at line breaks |
| `x` | Expanded syntax: whitespace and `#` comments in the pattern are ignored |
PostgreSQL 15 and later also accept a start position and an occurrence number before the flags, as in regexp_replace(source, pattern, replacement, start, N, flags). Check the documentation for your server version before relying on that form.
Extracting text with regexp_match
regexp_match(string, pattern [, flags]) returns the first match as a text[] array, or NULL if nothing matches. The array contents depend on the pattern:
- If the pattern has no capture groups, the array has one element: the whole match.
- If it has groups, the array has one element per group, in order, and the whole match is not included.
SELECT regexp_match('abc', 'b') AS no_group,
regexp_match('2026-11-27', '(\d+)-(\d+)-(\d+)') AS three_groups,
regexp_match('abc', 'x') AS no_match;The results are {b}, {2026,11,27} and NULL.
Because the result is an array, you index into it with [n], starting at 1. Wrap the call in parentheses first:
SELECT (regexp_match('order #1234 shipped', '#(\d+)'))[1] AS order_number;The result is 1234. If there is no match, regexp_match returns NULL, and indexing a NULL array also gives NULL, so you don't need a separate check for that case.
A group that exists in the pattern but takes no part in the match yields a NULL element, not an empty string:
SELECT regexp_match('ab', '(a)(x)?(b)') AS optional_group;The result is {a,NULL,b}.
substring with a pattern
For a single value, substring(string FROM pattern) is shorter. It returns the first capture group if the pattern has one, otherwise the whole match, and NULL if nothing matches.
SELECT substring('order #1234 shipped' FROM '#(\d+)') AS order_number;The result is 1234.
Getting every match
regexp_match stops after the first match. To get all matches, use regexp_matches with the g flag. It is a set-returning function, so it produces one row per match, each row being a text[].
SELECT match[1] AS number
FROM regexp_matches('a1b22c333', '\d+', 'g') AS t(match);This returns three rows: 1, 22, 333. Without g, regexp_matches returns at most one row.
PostgreSQL 15 added regexp_count, regexp_instr and regexp_substr, which count matches, find a match position, and return a match as plain text.
Splitting on a pattern
When the delimiter is not a fixed string, split with a regex:
SELECT regexp_split_to_array('a1b22c', '\d+') AS parts,
regexp_split_to_table('a1b22c', '\d+') AS one_per_row;The first column is {a,b,c}. The second produces rows a, b and c. Because the second is a set-returning function in the select list, the first column repeats on each row. For fixed delimiters, split_part and string_to_array from the earlier chapter are simpler.
Choosing the right tool
Edge cases and common errors
Greedy matching. Quantifiers such as * and + match as much as they can. Add ? after a quantifier to make it match as little as possible.
SELECT regexp_replace('<b>bold</b>', '<.*>', '', 'g') AS greedy,
regexp_replace('<b>bold</b>', '<.*?>', '', 'g') AS lazy;The greedy pattern removes the entire string and returns an empty string. The lazy pattern removes each tag separately and returns bold. In PostgreSQL, a pattern takes the greediness of its first quantified part, so mixing greedy and lazy quantifiers in one pattern can give surprising results. Prefer one style per pattern.
Forgetting to anchor. ~ '\d{5}' matches any string containing five digits, including a 12-digit number. For a postal-code check, write '^\d{5}$'.
Parentheses around regexp_match. regexp_match(...)[1] is a syntax error. Write (regexp_match(...))[1].
Treating group results as strings. The result is always text[]. Cast elements when you need numbers, for example ((regexp_match(s, '(\d+)'))[1])::int.
NULL input. Every function here returns NULL for a NULL string, and a ~ test on NULL gives NULL, which a WHERE clause treats as not true. Rows with NULL are dropped by both ~ and !~.
Speed. A regex test must examine each row's text. An ordinary B-tree index on the column cannot help a ~ filter. A trigram index from pg_trgm can support ~ and ~*, as covered in the indexing chapter. Patterns that begin with a wildcard or have heavy nested repetition can be slow on long strings, and PostgreSQL has no regex time limit other than statement_timeout.
Practice
Exercise
A column phone holds values like '(555) 010-1234'. Write an expression that returns the area code (555) as text. What does it return for the value 'n/a'?
Show answer
SELECT (regexpmatch(phone, '^\((\d{3})\)'))[1] AS areacode FROM contacts; (or substring(phone FROM '^\((\d{3})\)')). For '(555) 010-1234' it returns 555. For 'n/a' the pattern does not match, so regexp_match returns NULL and the indexed result is NULL.
Exercise
What do these two expressions return, and why? (1) regexp_replace('a-b-c', '-', '+') (2) 'Order 7' ~ '^\d+$'
Show answer
(1) 'a+b-c'. Without the g flag, only the first match is replaced. (2) false. The pattern is anchored with ^ and $ so the whole string must be digits, but the string starts with letters and contains a space.
Exercise
You want to find all the numbers in 'x=10, y=200' as separate rows. Which function and flag do you use, and what rows come back?
Show answer
regexpmatches with the g flag: SELECT m[1] FROM regexpmatches('x=10, y=200', '(\d+)', 'g') AS t(m); It returns two rows, 10 and 200.