REGEXP_REPLACE(string, pattern, replacement) replaces every match of the pattern. DuckDB's regexp_replace() replaces only the first match unless you pass the 'g' option. Group references are written $1 in Tableau and \1 in DuckDB.
Updated · Checked on the xmetric engine
What is the syntax?
REGEXP_REPLACE(string, pattern, replacement)
string
the text.
pattern
a constant regular expression.
replacement
the text to insert; $1, $2 refer to capture groups.
Returns the string with every match replaced. Null if the string is null.
What does it return, and what is the SQL?
Each example runs on the same 7 sample rows twice: the Tableau formula on the xmetric engine, and the SQL in DuckDB.
How do I mask every digit in a code?
Tableau
REGEXP_REPLACE([Code], '\d', '#')
SQL (DuckDB)
SELECTregexp_replace(Code, '\d', '#', 'g') AS result
FROM input
ORDERBY id
C-301-yz-9 becomes C-###-yz-#.
Code
Result
A-12-x
A-##-x
B-71
B-##
C-301-yz-9
C-###-yz-#
a_1
a_#
X
X
D-4-y
D-#-y
null
✓ The Tableau formula and the SQL return the same 7 rows.
Where does a straight translation go wrong?
Common mistake
Why does DuckDB mask only the first digit?
Without 'g', regexp_replace stops after one match: A-12-x becomes A-#2-x. Tableau replaces them all.
Tableau
REGEXP_REPLACE([Code], '\d', '#')
Tempting SQL
SELECTregexp_replace(Code, '\d', '#') AS result
FROM input
ORDERBY id
SQL that matches
SELECTregexp_replace(Code, '\d', '#', 'g') AS result
FROM input
ORDERBY id
Code
Tableau
Tempting SQL
SQL that matches
A-12-x
A-##-x
A-#2-x
A-##-x
B-71
B-##
B-#1
B-##
C-301-yz-9
C-###-yz-#
C-#01-yz-9
C-###-yz-#
a_1
a_#
a_#
a_#
X
X
X
X
D-4-y
D-#-y
D-#-y
D-#-y
null
null
null
✓ The SQL that matches returns the Tableau result on every row; the marked cells are where the tempting SQL differs.
Common mistake
Why does $2 come out literally in DuckDB?
DuckDB (RE2) writes group references as \1, \2; $2 is plain text there.
Tableau
REGEXP_REPLACE([Code], '(\w)-(\d+)', '$2/$1')
Tempting SQL
SELECTregexp_replace(Code, '(\w)-(\d+)', '$2/$1', 'g') AS result
FROM input
ORDERBY id
SQL that matches
SELECTregexp_replace(Code, '(\w)-(\d+)', '\2/\1', 'g') AS result
FROM input
ORDERBY id
Code
Tableau
Tempting SQL
SQL that matches
A-12-x
12/A-x
$2/$1-x
12/A-x
B-71
71/B
$2/$1
71/B
C-301-yz-9
301/C-y9/z
$2/$1-y$2/$1
301/C-y9/z
a_1
a_1
a_1
a_1
X
X
X
X
D-4-y
4/D-y
$2/$1-y
4/D-y
null
null
null
✓ The SQL that matches returns the Tableau result on every row; the marked cells are where the tempting SQL differs.
How do I reorder parts with capture groups?
Every match is rewritten, so both pairs in C-301-yz-9 move. Columns 1 to 7 are the sample rows, by id.