Search code examples
postgresqlregexp-replace

Postgresql: inserting spaces between certain type of digits


Related to my previous posting Postgresql: removing spaces between certain type of digits, I want to do the opposite, namely to insert spaces between postal codes. I might have a column with an address such as '01031970 São Paulo SP, BR'.

I want to insert a space between the fourth and fifth numeric digit, i.e. '0103 1970 São Paulo SP, BR'.

Any ideas how to do it with regexp_replace?


Solution

  • With regexp:

    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)     
    

    Without regexp (may be a bit faster for larger data):

    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)