0

How can we convert a string of any length into a comma separated string with comma after every n characters. I am using Oracle 10g and above. I tried with REGEXP_SUBSTR but couldn't get desired result.

e.g.: for below string comma after every 5 characters.

input:

aaaaabbbbbcccccdddddeeeeefffff  

output:

aaaaa,bbbbb,ccccc,ddddd,eeeee,fffff,  

or

aaaaa,bbbbb,ccccc,ddddd,eeeee,fffff

Thanks in advance.

1

3 Answers 3

3

This can be done with regexp_replace, like so:

WITH sample_data AS (SELECT 'aaaaabbbbbcccccdddddeeeeefffff' str FROM dual UNION ALL
            SELECT 'aaaa' str FROM dual UNION ALL
            SELECT 'aaaaabb' str FROM dual)
SELECT str,
       regexp_replace(str, '(.{5})', '\1,')
FROM   sample_data;

STR                            REGEXP_REPLACE(STR,'(.{5})','\
------------------------------ --------------------------------------------------------------------------------
aaaaabbbbbcccccdddddeeeeefffff aaaaa,bbbbb,ccccc,ddddd,eeeee,fffff,
aaaa                           aaaa
aaaaabb                        aaaaa,bb

The regexp_replace simply looks for any 5 characters (.{5}), and then replaces them with the same 5 characters plus a comma. The brackets around the .{5} turn it into a labelled subexpression - \1, since it's the first set of brackets - which we can then use to represent our 5 characters in the replacement section.

You would then need to trim the extra comma off the resultant string, if necessary.

Sign up to request clarification or add additional context in comments.

Comments

0
SELECT RTRIM ( REGEXP_REPLACE('aaaaabbbbbcccccdddddeeeeefffff', '(.{5})' ,'\1,') ,',') replaced
FROM DUAL;

Comments

0

This worked for me:

WITH strlen AS
    (
        SELECT 'aaaaabbbbbcccccdddddeeeeefffffggggg'      AS input,
            LENGTH('aaaaabbbbbcccccdddddeeeeefffffggggg') AS LEN,
            5                                             AS part
        FROM dual
    )
    ,
    pattern AS
    (
        SELECT regexp_substr(strlen.input, '[[:alnum:]]{5}', 1, LEVEL)
            ||',' AS line
        FROM strlen,
            dual
            CONNECT BY LEVEL <= strlen.len / strlen.part
    )
SELECT rtrim(listagg(line, '') WITHIN GROUP (
ORDER BY 1), ',') AS big_bang$
FROM pattern ;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.