Use SQL to Replace Multiple Commas in a String with a Single Comma

拥有回忆 提交于 2020-01-07 06:47:19

问题


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

I would like to replace all consecutive commas with a single comma and a space.

The output should be:

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

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

I haven't tested it yet as I don't have access to the Oracle system yet.


回答1:


More simple solution with same output:

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

@Joseph B: Sorry I can not comment yet! So I post my answer here.

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;

You can check this SQLFiddle




回答2:


You can use the following query ...

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;

to get the following output:

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

Here's the SQL Fiddle.

References:

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


来源:https://stackoverflow.com/questions/23189365/use-sql-to-replace-multiple-commas-in-a-string-with-a-single-comma

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!