How do I refer to capture groups in a MySQL regex?

(Old question, but top search result)

For MySQL 8:

SELECT REGEXP_REPLACE('stackoverflow','(.{5})(.*)','$2$1');
-- "overflowstack"

You can create capture groups with (), and you can refer to them using $1, $2, etc.

For MariaDB, capturing is done in REGEXP_REPLACE with \\1, \\2, etc. respectively.

Leave a Comment