跳到主要内容
版本: 最新版本-3.5

replace

将字符串中出现的所有字符替换为另一个字符串。此函数在搜索 pattern 时执行区分大小写的匹配。

此函数从 v3.0 版本开始支持。

注意:在 3.0 之前,此函数被实现为 regexp_replace

语法

VARCHAR replace(VARCHAR str, VARCHAR pattern, VARCHAR repl)

参数

  • str:原始字符串。

  • pattern:要替换的字符。请注意,这不是正则表达式。

  • repl:用于替换 pattern 中字符的字符串。

返回值

返回替换了指定字符的字符串。

如果任何参数为 NULL,则结果为 NULL。

如果未找到匹配的字符,则返回原始字符串。

示例

-- Replace '.' in 'a.b.c' with '+'.

MySQL > SELECT replace('a.b.c', '.', '+');
+----------------------------+
| replace('a.b.c', '.', '+') |
+----------------------------+
| a+b+c |
+----------------------------+

-- No matching characters are found and the original string is returned.

MySQL > SELECT replace('a b c', '', '*');
+----------------------------+
| replace('a b c', '', '*') |
+----------------------------+
| a b c |
+----------------------------+

-- Replace 'like' with an empty string.

MySQL > SELECT replace('We like StarRocks', 'like', '');
+------------------------------------------+
| replace('We like StarRocks', 'like', '') |
+------------------------------------------+
| We StarRocks |
+------------------------------------------+

-- No matching characters are found and the original string is returned.

MySQL > SELECT replace('He is awesome', 'handsome', 'smart');
+-----------------------------------------------+
| replace('He is awesome', 'handsome', 'smart') |
+-----------------------------------------------+
| He is awesome |
+-----------------------------------------------+

关键字

REPLACE, replace