使用SQL以单个逗号替换字符串中的多个逗号

时间:2014-04-21 01:05:06

标签: sql oracle oracle-sqldeveloper

输入:嗨,你好吗?好的,谢谢,,,,,,詹姆斯,阿登。

我想用一个逗号和一个空格替换所有连续的逗号。

输出应为:

嗨,你好吗?好的,谢谢,詹姆斯,阿登。

SELECT REGEXP_REPLACE('Hi,,How are you? Fine, thanks ,, ,  ,,,, , James,Arden.', ',,+', ', ') FROM DUAL;

我还没有测试过,因为我还没有访问过Oracle系统。

2 个答案:

答案 0 :(得分:1)

具有相同输出的更简单的解决方案:

Hi, How are you? Fine, thanks, James, Arden.

@Joseph B:对不起,我还不能发表评论!所以我在这里发表我的答案。

SELECT 
        REGEXP_REPLACE(
            REGEXP_REPLACE('Hi,,How are you? Fine, thanks ,, ,  ,,,, , James,Arden.', ', | ,', ','), --Replace ', ' and ' ,' with ','
        ',{1,}', ', ') single_comma_text --Replace one or more comma with comma followed by space
FROM DUAL;

您可以查看SQLFiddle

答案 1 :(得分:0)

您可以使用以下查询...

SELECT 
    REGEXP_REPLACE(
        REGEXP_REPLACE(
            REGEXP_REPLACE('Hi,,How are you? Fine, thanks ,, ,  ,,,, , James,Arden.', ', | ,', ','), --Replace ', ' and ' ,' with ','
        ',{2,}', ', '), --Replace 2 or more occurrences of comma with single comma followed by space
    ',(.)', ', \1') single_comma_text --Replace comma followed by any character with comma followed by space followed by character
FROM DUAL;

获取以下输出:

Hi, How are you? Fine, thanks, James, Arden.

这里是 SQL Fiddle

<强>参考

  1. REGEXP_REPLACE on Oracle® Database SQL Reference
  2. Multilingual Regular Expression Syntax on Oracle® Database SQL Reference