oracle sql中的regex_replace

时间:2019-03-19 10:12:04

标签: sql regex oracle

我不是正则表达式专家,在Oracle中,我想使用regexp_replace(0函数在文本中查找字符串。

要查找的字符串的开头为“ [”,结尾为“]”。 在“ [”和“]”之间,您会找到字母和“ _”字符。

所以,如果我有这段文字:

ID为[tag1],[tag2],[tag3] ..... [tagN]

如何删除[和]?

我需要获得

ID为tag1,tag2,tag3 ....,tagN

我尝试过:

select REGEXP_REPLACE('the ID's are [tag1] , [tag2] , [tag3].........','[(.*?)]') from dual

但是它不起作用。

包含文本的字段位于一个至少包含一百万条记录的表中。

3 个答案:

答案 0 :(得分:1)

您可以使用

with t(str) as
(
 select 'the ID''s are [tag1] , [tag2] , [tag3]' from dual
), t2(str2) as
(
 select regexp_substr(str,'[^\[]+', 1, 1) from t
)
select concat( regexp_substr(str,'[^\[]+', 1), 
         listagg(replace(regexp_substr(str,'[^\[]*.[^\]]', 1, level),']',''),',') 
              within group (order by 1) ) 
       as "Derived String"       
  from t 
 cross join t2 
 connect by level <= regexp_count(str,'\[');

Derived String
---------------------------
the ID's are tag1,tag2,tag3

Demo

编辑1 如果您只想动态提取标签,则为

tag1 tag2 tag3 .... tag n

然后在下面使用

with t(str) as
(
 select 'the ID''s are [tag1] , [tag2] , [tag3]' from dual
)
select   listagg(replace(regexp_substr(str,'[^\[]*.[^\]]', 1, level),']',''),' ') 
              within group (order by 1) 
       as "Derived String"       
  from t  
 connect by level <= regexp_count(str,'\[') 

编辑2 (由于最后一条评论):

尝试在下面使用

with t(a,b) as
(
 select 'the ID''s are [tag1] , [tag2] , [tag3]' as a,
        'the ID''s are [tag4] , [tag5] , [tag6], [tag7]' as b
   from dual
)
select   listagg(replace(regexp_substr(a,'[^\[]*.[^\]]', 1, level),']',''),' ') 
              within group (order by 1) 
       as "Derived String 1",
         listagg(replace(regexp_substr(b,'[^\[]*.[^\]]', 1, level),']',''),' ') 
              within group (order by 1) 
       as "Derived String 2"       
  from t  
 connect by level <= greatest(regexp_count(a,'\['),regexp_count(b,'\['));

Derived String 1                  Derived String 2
---------------------------       ---------------------------   
tag1 tag2 tag3                    tag4 tag5 tag6 tag7

答案 1 :(得分:1)

回答原始问题:

with s as (select 'the ID''s are [tag1] , [tag2] , [tag3]' str from dual)
select
regexp_replace(regexp_replace(regexp_replace(str, '\[.*?\]', '221'  , 1, 1)
                                                , '\[.*?\]', '342'  , 1, 1)
                                                , '\[.*?\]', '13412', 1, 1) as str
from s;

STR
------------------------------
the ID's are 221 , 342 , 13412

答案已更改:

with s as (select 'the ID''s are [tag1] , [tag2] , [tag3]' str from dual)
select
replace(replace(str, ']'), '[') str
from s;

STR
-------------------------------
the ID's are tag1 , tag2 , tag3

答案 2 :(得分:1)

为什么不只替换[]

select translate(text, 'x[]', 'x')