Sub topic 12
Regular expressions: `~`, `regexp_replace` and `regexp_match`
Assume you know SELECT, WHERE, LIKE, text values, and NULL in PostgreSQL. This chapter focuses on POSIX regular expressions, which describe text patterns more precisely than LIKE.
Matching with regular-expression operators
The ~ operator returns true when a string matches a case-sensitive regular expression. The ~* operator performs a case-insensitive match. Their negated forms are !~ and !~*.
SELECT email
FROM customers
WHERE email ~ '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$';The pattern uses these parts:
^means the beginning of the string.$means the end of the string.+means one or more occurrences.\.means a literal period. In an extended string literal, write this asE'\\.'.
A regular expression without ^ or $ can match a substring. For example, name ~ 'cat' matches both cat and concatenate.
Use ~* when letter case should not matter:
SELECT product_name
FROM products
WHERE product_name ~* '^(phone|tablet)$';Replacing matches with `regexp_replace`
regexp_replace returns a changed copy of a string. Its basic form replaces the first match:
SELECT regexp_replace('Order 123 is pending', '[0-9]+', '456');This returns Order 456 is pending. Add the g flag to replace every match:
SELECT regexp_replace('2026-01-05, 2026-02-10',
'[0-9]{4}-[0-9]{2}-[0-9]{2}',
'[date]',
'g') AS cleaned;Parentheses create capture groups. A replacement can refer to captured text with \1, \2, and so on. Extended string syntax, written with E, makes the backslashes explicit:
SELECT regexp_replace(
'2026-11-27',
E'(\\d+)-(\\d+)-(\\d+)',
E'\\3/\\2/\\1'
) AS reordered;The result is 27/11/2026. The three groups capture the year, month, and day, and the replacement writes them in reverse order.
Extracting matches with `regexp_match`
regexp_match returns the captured groups from the first match as a text[] array. If the pattern does not match, it returns NULL.
SELECT (regexp_match('order #1234 shipped', E'#(\\d+)'))[1]
AS order_number;The pattern contains one capture group, so array element [1] contains 1234. PostgreSQL arrays use one-based indexes.
The function is useful when you need a value from a larger string:
SELECT id,
(regexp_match(message, E'priority: (high|medium|low)'))[1]
AS priority
FROM support_messages
WHERE message ~ E'priority: (high|medium|low)';The WHERE clause keeps rows that contain the pattern. The function then extracts the selected priority.
Choosing the operation
| Need | Best tool |
|---|---|
| Test whether text matches | `~` or `~*` |
| Replace matching text | `regexp_replace` |
| Extract captured text | `regexp_match` |
Exercise
Write a query that changes every sequence of one or more whitespace characters in Hello PostgreSQL to a single hyphen.
Show answer
SELECT regexp_replace('Hello PostgreSQL', E'\\s+', '-', 'g');