0

Suppose I have a string such as:

abcdefghi

and I would like to reformat it as:

abc def ghi

(that is, I have added some formatting spaces to the string).

Is there a PostgreSQL function which will do that? Something like:

reformat(abcdefghi,'xxx xxx xxx')

I know there isn’t the above function, but there might be a built in function to do something like that.

If not, I am happy to write such a function, but I though I would check.

  • 2
    So you want to add a space after three characters? Does it need to work with any length (so abcdefghijklmno will beabc def ghi jkl mno). What should happen if the string length is not a multiple of 3? – a_horse_with_no_name Mar 27 '18 at 11:29
  • String Functions and Operators section of the documentation lists all related functions. You can use either regexp_replace or format function for this kind of problems. – Sahap Asci Mar 27 '18 at 12:15
0

Use regexp_replace

SELECT regexp_replace('abcdefghiabcdefghi', '(.{3})', '\1 ', 'g');
      regexp_replace      
--------------------------
 abc def ghi abc def ghi 
(1 row)

This inserts a space every three characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.