Write the Code. Change the World.

3月 09

有这样一个场景。mysql 数据库有个表的字段里边存了一些图片链接信息。关键是这些链接信息是整个域名都包含在内的。如果有一天,域名换了,随着新域名一起,文件也搬过来了。这个时候,就需要把这个字段里边的域名信息全部替换掉。这个时候,REGEXP_REPLACE 就很有用了。

先看看截图和 sql,就知道这个的好用了。

https://blog.vini123.com/wp-content/uploads/2023/03/1678375647317.jpg

UPDATE wp_posts set `post_content` = REGEXP_REPLACE(`post_content`, 'blog.vi', 'blog1.vi') WHERE true;

我这里数据少,之前全部给替换了。

REGEXP_REPLACE

regexp_replace(source, pattern, replace_string, occurrence)

参数说明:

  • source: string类型,要替换的原始字符串
  • pattern: string类型常量,要匹配的正则模式,pattern为空串时抛异常
  • replace_string:string,将匹配的pattern替换成的字符串
  • occurrence: bigint类型常量,必须大于等于0。大于0,表示将第几次匹配替换成replace_string,等于0表示替换掉所有的匹配子串,其它类型或小于0抛异常

返回值:
将source字符串中匹配pattern的子串替换成指定字符串后返回。当输入source, pattern, occurrence参数为NULL时返回NULL,若replace_string为NULL且pattern有匹配,返回NULL,replace_string为NULL但pattern不匹配,则返回原串。