如何使用REGEXP_REPLACE从每一端删除重复的逗号和修剪?

时间:2016-02-08 17:49:34

标签: sql oracle regexp-replace

我需要将几个字段连接在一起,这可能是也可能不是null。我最终可能会得到一个字符串:',, c ,, e ,,'我实际上想要显示为'c,e'。

我可以通过regexp_replacetrim

的组合获得此功能
with sd as (select 'a,b,c' str from dual union all
            select 'a' str from dual union all
            select null str from dual union all
            select 'a,,,d' from dual union all
            select 'a,,,,e,f,,'from dual union all
            select ',,,d,,f,g,,'from dual)
select str,
       regexp_replace(str, '(,)+', '\1') new_str,
       trim(both ',' from regexp_replace(str, '(,)+', '\1')) trimmed_new_str
from   sd;

STR         NEW_STR     TRIMMED_NEW_STR
----------- ----------- ---------------
a,b,c       a,b,c       a,b,c          
a           a           a              

a,,,d       a,d         a,d            
a,,,,e,f,,  a,e,f,      a,e,f          
,,,d,,f,g,, ,d,f,g,     d,f,g  

但我觉得它应该只用一个regexp_replace来实现,只有我无法为我的生活做好如何做到这一点!

有可能吗?如果是这样,怎么样?

2 个答案:

答案 0 :(得分:4)

<强>查询:

with sd as (select 'a,b,c' str from dual union all
            select 'a' from dual  union all
            select null from dual union all
            select 'a,,,d,' from dual  union all
            select ',a,,,d' from dual  union all
            select ',a,,,d,' from dual  union all
            select ',,,a,,,d,,,' from dual  union all
            select ',a,,,,,e,f,,' from dual union all
            select ',,d,,f,g,,' from dual )
select str,
       regexp_replace(str, '^,+|,+$|,+(,\w)','\1') new_str
from   sd;

<强>结果:

str             new_str
-----------------------
a,b,c           a,b,c
a               a
(null)          (null)  
a,,,d,          a,d
,a,,,d          a,d
,a,,,d,         a,d
,,,a,,,d,,,     a,d
,a,,,,,e,f,,    a,e,f
,,d,,f,g,,      d,f,g

<强>模式:

  ^,+       matches commas at the beginning
  |         OR
  ,+$       matches commas at the end
  |         OR
  ,+(,\w)   matches several commas followed by a single comma and a word.

仅替换上面的第一个子表达式,即逗号和单词。

答案 1 :(得分:-1)

试一试:

with sd as (select 'a,b,c' str union all
            select 'a' union all
            select null union all
            select 'a,,,d' union all
            select 'a,,,,,e,f,,' union all
            select ',,,d,,f,g,,')
select str,
       regexp_replace(str, '(,){2,}', '\1', 1, 0) new_str,
       trim(both ',' from regexp_replace(str, '(,){2,}', '\1', 1, 0)) trimmed_new_str
from   sd;