1

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.

user311509
  • 2,856
  • 12
  • 52
  • 69

2 Answers2

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

MinhD
  • 1,790
  • 11
  • 14
  • Great. How can I return those records that have consecutive commas two or more eg ,,? regardless of the spaces between them: , , – user311509 Apr 21 '14 at 06:30
  • Replace all space between commas, then use REGEXP_LIKE in WHERE clause to check if the String have 2 or more consecutive commas, ignore space: `WHERE REGEXP_LIKE(REGEXP_REPLACE(multi_commas_column, ', | ,', ','), ',{2,}')`. Check this [SQLFiddle](http://www.sqlfiddle.com/#!4/d41d8/28101) – MinhD Apr 21 '14 at 07:04
  • @user311509: Could you please accept this answer? This will help others with the same problem. – MinhD Apr 22 '14 at 06:10
0

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
Joseph B
  • 5,519
  • 1
  • 15
  • 19