2014-04-21 102 views
0

输入:嗨,你好吗?很好,谢谢,,,,, James,Arden。使用SQL以单个逗号替换字符串中的多个逗号

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

输出应该是:

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

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

我没有测试它尚未因为我没有访问Oracle系统呢。

+0

请看:http://sqlfiddle.com/#!4/d41d8/28054 –

回答

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

+0

大。我怎样才能返回连续逗号两个或更多例如,,的记录?不管它们之间有空格:, – user311509

+0

替换逗号之间的所有空格,然后在WHERE子句中使用REGEXP_LIKE来检查字符串是否有2个或更多连续逗号,忽略空格:'WHERE REGEXP_LIKE(REGEXP_REPLACE(multi_commas_column,',|,', ,','),',{2,}')'。检查此[SQLFiddle](http://www.sqlfiddle.com/#!4/d41d8/28101) – MinhD

+0

@ user311509:您能否接受此答案?这将有助于其他人解决同样的问题。 – MinhD

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
相关问题