跳到主要内容

REGEXP_REPLACE

描述

字符串 STR 进行正则匹配,将匹配 pattern 的部分替换为 repl。

  • 字符集匹配需要使用 Unicode 标准字符类型。例如,匹配中文请使用 \p{Han}

语法

REGEXP_REPLACE(<str>, <pattern>, <repl>)

参数

参数描述
<str>需要进行正则匹配的列。
<pattern>目标模式。
<repl>用于替换匹配模式的字符串。

返回值

替换之后的结果。类型是 Varchar

举例

mysql> SELECT regexp_replace('a b c', ' ', '-');
+-----------------------------------+
| regexp_replace('a b c', ' ', '-') |
+-----------------------------------+
| a-b-c |
+-----------------------------------+

mysql> SELECT regexp_replace('a b c', '(b)', '<\\1>');
+----------------------------------------+
| regexp_replace('a b c', '(b)', '<\1>') |
+----------------------------------------+
| a <b> c |
+----------------------------------------+

mysql> select regexp_replace('这是一段中文This is a passage in English 1234567', '\\p{Han}+', '123');
+---------------------------------------------------------------------------------------------+
| regexp_replace('这是一段中文This is a passage in English 1234567', '\p{Han}+', '123') |
+---------------------------------------------------------------------------------------------+
| 123This is a passage in English 1234567 |
+---------------------------------------------------------------------------------------------+