You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Postgres使用regexp_replace删除括号内容如何避免产生多余双空格

原有写法失效原因

你嵌套的第二个regexp_replace未添加全局替换参数g,且仅匹配单个空白符,因此只能处理一处多余空格,多括号场景下自然会残留连续空格。


可行解法

解法1:两步处理(兼容性最强)

先移除所有括号内容,再将所有连续的多个空白符替换为单个空格,适配任意多括号场景:

select regexp_replace(
    regexp_replace('john (junior) jones (hughes) smith', '\([^)]*\)', '', 'g'),
    '\s+', ' ', 'g'
);

执行结果为:john jones smith

如果需要兼容括号出现在字符串首尾的场景,在外层加trim()移除首尾多余空格即可:

select trim(
    regexp_replace(
        regexp_replace('(prefix) john (junior) jones (hughes) smith (suffix)', '\([^)]*\)', '', 'g'),
        '\s+', ' ', 'g'
    )
);

解法2:一步正则替换(写法更简洁)

直接匹配「可选前置空格+括号内容+可选后置空格」的整体,替换为单个空格,无需嵌套调用:

select trim(regexp_replace('john (junior) jones (hughes) smith', '\s*\([^)]*\)\s*', ' ', 'g'));

内容的提问来源于stack exchange,提问作者nimgwfc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 01:39:01