Home > OS >  How do I insert a character every 2 spaces in a string?
How do I insert a character every 2 spaces in a string?

Time:08-12

I have a table with a 50 CHAR column, with a content like

AABB
AA
CCXXDD

It's a string used like an array of 25 elements CHAR 2.

I need to insert a comma every 2 characters

AA,BB
AA
CC,XX,DD

It there a system function or I need to create one?

CodePudding user response:

We can do a regex replacement here:

SELECT col, RTRIM(REGEXP_REPLACE(col, '(..)', '\1,'), ',') AS col_out
FROM yourTable;

The above logic inserts a comma after every two characters. For inputs having an even number of characters, this leaves an unwanted dangling comma on the right, which we remove using RTRIM().

  • Related