首页 > 解决方案 > Postgres 正则表达式停止创建双倍空间

问题描述

我有一个看起来像这样的查询:

select regexp_replace('john (junior) jones','\([^)]*\)','','g');
  regexp_replace  
------------------
 john  jones

如您所见,此查询删除了括号中的值,但会导致剩余的双倍空格。

有没有简单的方法解决这个问题?

到目前为止,我有这个,它在一定程度上有效:

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

上面的工作但不是当我通过这样的事情时:

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

标签: postgresql

解决方案


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

  regexp_replace  
══════════════════
 john jones smith
(1 row)

解释正则表达式:

  • 任意数量的空格,后跟左括号 ( *\()
  • 不是右括号 ( [^)]*)的任意数量的字符
  • 右括号和任意多个空格 ( \) *)

那被一个空格代替。


推荐阅读