歪麦博客

MySQL 正则表达式替换

先说结论:

  1. 对于 MySQL 8+, 用REGEXP_REPLACE()函数
  2. 对于 MySQL 5 及以前版本,用用户自定义函数 (user-defined function,简称UDF),如:mysql-udf-regexp

本文只说明 MySQL 8+ 中REGEXP_REPLACE()函数的用法,不对 UDF 进行说明,请自行参考 GitHub 链接。

用法

REGEXP_REPLACE(expr, pat, repl[, pos[, occurrence[, match_type]]])

如上:

示例

替换字符串:

-- 以下输出为:the quick brown dog
SELECT REGEXP_REPLACE('the quick brown fox', '(.*?)(fox)' , '$1dog'  ) AS demo;

替换字段:

-- 假设原本字段内容为:100 test of regex,以下输出为:100 test
update post set title =  REGEXP_REPLACE(title, '([0-9]+) test of regex', '$1 test') where id = 1;

参考资料:

退出移动版