How to do a regular expression replace in MySQL?

Solution 1:

MySQL 8.0+:

You can use the native REGEXP_REPLACE function.

Older versions:

You can use a user-defined function (UDF) like mysql-udf-regexp.

Solution 2:

If you are using MariaDB or MySQL 8.0, they have a function

REGEXP_REPLACE(col, regexp, replace)

See MariaDB docs and PCRE Regular expression enhancements

Note that you can use regexp grouping as well (I found that very useful):

SELECT REGEXP_REPLACE("stackoverflow", "(stack)(over)(flow)", '\\2 - \\1 - \\3')

returns

over - stack - flow