具有空位置的Oracle PL / SQL Tokenize字符串

时间:2014-12-01 09:38:31

标签: oracle plsql

我是这样的字符串:

AAA,BBB DDD ,,

我想用逗号来标记它并检索一个这样的表:

VALUE  LEVEL 
AAA    1
BBB    2
(null) 3
DDD    4

我需要知道String并且在找到它的女巫位置,不会错过null String。

我尝试过这样的代码,但我想念空位:

SELECT    regexp_substr ('AAA,BBB,,DDD', '[^,]+', 1, level), level
FROM    dual
CONNECT BY LEVEL <= LENGTH(regexp_replace ('AAA,BBB,,DDD', '[^,]+'));

输出是这样的:

VALUE LEVEL
AAA   1
BBB   2
DDD   3

3 个答案:

答案 0 :(得分:1)

SELECT token, lvl FROM (
  SELECT    regexp_substr ('AAA,BBB,,DDD', '[^,]*', 1, LEVEL) token, LEVEL lvl,
            lag(regexp_substr ('AAA,BBB,,DDD', '[^,]*', 1, LEVEL)) over(order by level) prev_token
  FROM    dual
  CONNECT BY LEVEL <= LENGTH(regexp_replace ('AAA,BBB,,DDD', '[^,]+'))*2
) WHERE prev_token is null;

答案 1 :(得分:1)

在oracle 11g和更高版本中你可以做类似这样的查询:

with      
  tab1(pointer,test,split_test) as
  (select
    1 as pointer,test,substr(test,0,case when instr(test,',',1,1) = 0 then LENGTH(test)
                        else instr(test,',',1,1)-1 end) split_test from table1
  union all
  select
  pointer + 1 as pointer,test,
  substr(test,instr(test,',',1,pointer) + 1,case when instr(test,',',1,pointer + 1) = 0 then LENGTH(test) else
   instr(test,',',1,pointer + 1) - instr(test,',',1,pointer) - 1 end) split_test
  from tab1 where pointer - 1 < LENGTH(test)-LENGTH(REPLACE(test,',','')))
select split_test as "value",pointer as "level" from tab1;

SQL Fiddle

答案 2 :(得分:1)

另一个简单的答案是用逗号(,)替换逗号(, ),如下所示

SELECT    trim(regexp_substr (replace('AAA,BBB,,DDD',',',', '), '[^,]+', 1, level)), level
FROM    dual
CONNECT BY LEVEL <= REGEXP_COUNT (replace('AAA,BBB,,DDD',',',', '), '[^,]+');

这也有效http://sqlfiddle.com/#!4/b255d/26