查询以匹配模式替换字符串

时间:2014-06-18 04:00:57

标签: regex oracle replace

我有一个如下字符串。

'comp'为“COMPUTER”,'ms'为“MOUSE”,'keybr'为“KEYBOARD”,'MONT'为“MONITOR”,

是否可以编写查询以便我将结果作为

'comp','ms','keybr','MONT',

我可以使用REPLACE查询将字符串“as”替换为空字符串。 但是如何删除双引号内的字符串?

任何人都可以帮我这样做吗? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

select replace(
               regexp_replace('''comp'' as "COMPUTER"'
                              , '(".*")'
                              ,null)
               ,' as '
               ,null)
from dual

正则表达式'(".*")'选择双引号中的文本。

编辑:

正则表达式替换了匹配模式的整个长度。因此,我们可能需要首先使用逗号作为分隔符来标记字符串并应用正则表达式。稍后加入。(LISTAGG

WITH str_tab(str1, rn) AS
(SELECT regexp_substr(str, '[^,]+', 1, LEVEL), -- delimts
        LEVEL 
   FROM (SELECT '''comp'' as "computer",''comp'' as "computer"' str
           FROM dual) tab
CONNECT BY LEVEL <= LENGTH(str) - LENGTH(REPLACE(str, ',')) + 1)
SELECT listagg(replace(
               regexp_replace(str1
                              , '(".*")'
                              ,null)
               ,' as '
               ,null), ',') WITHIN GROUP (ORDER BY rn) AS new_text
  FROM str_tab;

EDIT2:

来自@EatAPeach的cleaner approach

with x(y) as (
  select q'<'comp' as "COMPUTER",'ms' as "MOUSE" ,'keybr' as "KEYBOARD",'MONT' as "MONITOR",>'
  from dual
)
select y,
       regexp_replace(y, 'as ".*?"' ,null)
from x;