replace(text, text, text) — 替换字符串中的所有匹配
最后更新:2026-11-04
replace(text, text, text) — 替换字符串中的所有匹配
replace() 把字符串里所有出现的 from 子串替换成 to,返回新字符串。它是清理脏数据、抹掉敏感信息、统一分隔符的常用手段;注意它会替换全部匹配,而不是只替换第一处,所以做"只换一次"的操作时得另想办法。
| 类别 | function |
|---|---|
| 示例语言 | SQL |
📝 语法
replace(string text, from text, to text) → text
⚙️ 参数
| string text | 原始字符串。类型 text。 |
|---|---|
| from text | 要被替换掉的子串(区分大小写)。类型 text。 |
| to text | 替换后的新子串,传空字符串表示删除。类型 text。 |
返回值:text —— 替换后的字符串。任一入参为 NULL 时返回 NULL。
▶ 示例
直接在浏览器里运行真 PostgreSQL 18(PGlite WASM,无需安装任何东西)——点 ▶ Run,结果显示在下方面板。
输出:
id | slug | slug_underscore | replaced
----+------------------------+------------------------+---------------------
1 | hello-world-postgresql | hello_world_postgresql | hi-world-postgresql
2 | hello-world-mysql | hello_world_mysql | hi-world-mysql
3 | no-match-here | no_match_here | no-match-here
(3 rows)
📌 要点
- replace() 替换全部匹配,不只是第一处。
- 匹配区分大小写,要做不区分大小写的替换请用 regexp_replace()。
- 任一入参为 NULL 时结果为 NULL;把 to 传空字符串即可实现删除。
💡 相关案例
更多实战案例即将补充。
📚 相关条目
❓ 常见问题
Q想把 "hello world" 换成 "hi world",但只换第一处,怎么写?
Areplace() 会全部替换。改用 regexp_replace(s, 'hello', 'hi')(不加 'g' 标志时只替换第一处),或 overlay() 精确覆盖指定位置。