Strings

REGEXP_REPLACE

Replaces the parts of a string that match a regular expression.

Syntax

REGEXP_REPLACE(<text>, '<pattern>', <to>)
REGEXP_REPLACE(<text>, '<pattern>', <to>, '<flags>')

Like REPLACE, but it looks for a pattern rather than exact text: [0-9] — any digit, ' +' — one or more spaces in a row. Without flags it replaces only the first occurrence; the 'g' flag replaces all of them, 'i' ignores case.

Data for the examples

employees

namedepartmentsalarybonusphone
Emmabackend1200300+44 7700 900123
Liambackend1000NULLNULL
Oliviafrontend1350150+44 7700 900456
Noahfrontend950NULL+44 7700 900789
Sophiadesign1200200NULL

These tables already exist in the sandbox — the examples below use them. Want to try this in your own database? Copy the SQL.

Digits to asterisks
SELECT REGEXP_REPLACE('Card 4242 4242', '[0-9]', '*', 'g') AS hidden;
hidden
Card **** ****
Only the digits of a phone number
SELECT name, phone,
REGEXP_REPLACE(phone, '[^0-9]', '', 'g') AS digits
FROM employees;
namephonedigits
Emma+44 7700 900123447700900123
LiamNULLNULL
Olivia+44 7700 900456447700900456
Noah+44 7700 900789447700900789
SophiaNULLNULL

[^0-9] means any character except a digit: the plus and the spaces disappear.

Several spaces into one
SELECT REGEXP_REPLACE('Emma Wilson', ' +', ' ', 'g') AS cleaned;
cleaned
Emma Wilson

Watch out

Without 'g', only the first occurrence is replaced: REGEXP_REPLACE('a1b2', '[0-9]', '') gives ab2.

A dot in a pattern means “any character”: REGEXP_REPLACE('v1.2.3', '.', '-', 'g') gives ------. Write the dot itself as '\.' — then you get v1-2-3.

To replace exact text, REPLACE is simpler and faster.

Related functions