regexp_replace() 是一个系统函数,用于使用 POSIX 正则表达式替换字符串中匹配的值。
regexp_replace() 在 PostgreSQL 8.1 中添加。
用法
regexp_replace (stringtext,patterntext,replacementtext[,flagstext] ) →text
PostgreSQL 15 及更高版本
regexp_replace (stringtext,patterntext,replacementtext[,startinteger] [,flagstext] ) →text
regexp_replace (stringtext,patterntext,replacementtext,startinteger,Ninteger[,flagstext] ) →text
命名参数从 PostgreSQL 18 开始可用。
可与 regexp_replace() 一起使用的标志列表可在 PostgreSQL 文档中找到:ARE 嵌入式选项字母。
变更历史
- PostgreSQL 18
- 添加了对参数名称的支持(提交 580f8727)
- PostgreSQL 15
- 添加了起始位置(参数
start)和匹配位置(参数N)(提交 64243370)
- 添加了起始位置(参数
- PostgreSQL 8.1
- 添加(初始提交 75a64eeb)
示例
regexp_replace() 的基本执行示例
postgres=# SELECT regexp_replace('foobar', 'f\w\w', 'moo');
regexp_replace
----------------
moobar
(1 row)
使用 'g'(“全局”)标志替换模式的多个出现
postgres=# SELECT regexp_replace('foobarboo flooobiloo', 'o{2,}', 'uu', 'g');
regexp_replace
---------------------
fuubarbuu fluubiluu
(1 row)
在 **PostgreSQL 15** 及更高版本中,可以可选地指定起始位置
postgres=# SELECT regexp_replace('foobarboo flooobiloo', 'o{2,}', 'uu', 3);
regexp_replace
----------------------
foobarbuu flooobiloo
(1 row)
要替换从指定起始位置开始的所有出现,请使用
postgres=# SELECT regexp_replace('foobarboo flooobiloo', 'o{2,}', 'uu', 3, 0, 'g');
regexp_replace
---------------------
foobarbuu fluubiluu
(1 row)
参考资料
- PostgreSQL 文档: 其他字符串函数
