使用Oracle正则表达式将字符串(由连续分隔符分隔)转换为行

时间:2013-04-23 02:16:48

标签: oracle

我有一个由Oracle中的连续分隔符代码(〜)分隔的通用字符串。对于例如字符串是'apple~apple ~~芒果~~ grape'。它需要转换成行,但需要注意的一件重要事情是分隔符是连续的代字号而不是单个代字号。输出应如下所示:

苹果〜橙

芒果

葡萄

使用instr和substr oracle函数已经完成了解决方法,但我需要使用Oracle regular expressins更清晰的解决方案。我尝试使用下面的查询,但没有得到正确的解决方案:

WITH str AS (SELECT 'apple~orange~~mango~~grapes' str FROM dual),
     cnt AS (SELECT LEVEL sno FROM dual CONNECT BY LEVEL < 5)
SELECT regexp_substr (str, '[^~]+', 1, sno) FROM str CROSS JOIN cnt;

2 个答案:

答案 0 :(得分:0)

尝试此操作(如果您希望任何字符串包含*, ^, #作为实际值,则可以使用,以外的任何字符,而不是,

WITH STR AS (SELECT REPLACE('apple~orange~~mango~~grapes','~~',',') STR FROM DUAL),
     CNT AS (SELECT LEVEL SNO FROM DUAL CONNECT BY LEVEL < 4)
SELECT REGEXP_SUBSTR (STR, '[^,]+', 1, SNO) FROM STR CROSS JOIN CNT;

您也可以将XML与oracle一起使用

WITH CTE AS (SELECT '"' 
             || REPLACE('apple~orange~~mango~~grapes','~~','","') 
             || '"' STR FROM DUAL)
select column_value str from cte, xmltable(str);

答案 1 :(得分:0)

试试这个,

select 
          t.str
         , regexp_substr (t.str, '[^~(?=~)]+', 1, rn) spl
    from YOURTABLE t
     cross
     join (select rownum rn
       from (select max (length (regexp_replace (t.str, '[^~~]+'))) + 1 mx
                     from YOURTABLE t
                  )
          connect by level <= mx
          )
   where regexp_substr (t.str,'[^~(?=~)]+' , 1, rn) is not null)