2

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

regexp_replace我可以通过和的组合得到这个trim

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只是我无法为我的生活解决它是如何完成的!

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

4

2 回答 2

5

询问:

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.

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

于 2016-02-09T06:53:14.053 回答
-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;
于 2016-02-08T18:23:45.610 回答