简体   繁体   English

Oracle SQL查询将字符串转换为逗号分隔的字符串,每n个字符后用逗号分隔

[英]Oracle SQL query to convert a string into a comma separated string with comma after every n characters

How can we convert a string of any length into a comma separated string with comma after every n characters. 我们如何将任何长度的字符串转换成逗号分隔的字符串,每隔n个字符用逗号分隔。 I am using Oracle 10g and above. 我正在使用Oracle 10g及更高版本。 I tried with REGEXP_SUBSTR but couldn't get desired result. 我尝试使用REGEXP_SUBSTR,但无法获得理想的结果。

eg: for below string comma after every 5 characters. 例如:对于每5个字符以下的字符串逗号。

input: 输入:

aaaaabbbbbcccccdddddeeeeefffff  

output: 输出:

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

or 要么

aaaaa,bbbbb,ccccc,ddddd,eeeee,fffff

Thanks in advance. 提前致谢。

This can be done with regexp_replace, like so: 可以使用regexp_replace来完成,如下所示:

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. regexp_replace只是查找任何5个字符( .{5} ),然后将它们替换为相同的5个字符和一个逗号。 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. .{5}周围的方括号将其转换为带标签的子表达式\\1 ,因为它是第一组方括号-然后我们可以用它来表示替换部分中的5个字符。

You would then need to trim the extra comma off the resultant string, if necessary. 然后,如果需要,您将需要修剪掉多余的逗号。

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

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 ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM