Postgresql:在某些类型的数字之间插入空格

Posted

技术标签:

【中文标题】Postgresql:在某些类型的数字之间插入空格【英文标题】:Postgresql: inserting spaces between certain type of digits 【发布时间】:2018-03-04 06:31:09 【问题描述】:

与我之前的帖子有关 Postgresql: removing spaces between certain type of digits, 我想做相反的事情,即在邮政编码之间插入空格。 我可能有一列地址,例如'01031970 São Paulo SP, BR'

我想在第四个和第五个数字之间插入一个空格,即 '0103 1970 São Paulo SP, BR'

任何想法如何使用regexp_replace 做到这一点?

【问题讨论】:

【参考方案1】:

使用正则表达式:

select regexp_replace(str, '(^.4)(.*)', '\1 \2')
from (
    values('01031970 Sao Paulo SP, BR')
    ) v(str);

       regexp_replace       
----------------------------
 0103 1970 Sao Paulo SP, BR
(1 row)     

没有正则表达式(对于较大的数据可能会快一点):

select concat(left(str, 4), ' ', right(str, -4))
from (
    values('01031970 Sao Paulo SP, BR')
    ) v(str);

           concat           
----------------------------
 0103 1970 Sao Paulo SP, BR
(1 row)

【讨论】:

以上是关于Postgresql:在某些类型的数字之间插入空格的主要内容,如果未能解决你的问题,请参考以下文章