2014-02-25 132 views
1

我一直都在這個問題上停留,希望得到一些幫助。我一直在閱讀我能找到的東西,但在我的情況下,我遇到了麻煩。Regexp_substr將字符串解析爲片段

我也有類似的記錄本:

A123-700 
A123-700/WORD-8 
A123/A456 
WORD-8/A456-800 

我需要打破這些成一個 「類型」 和 「系列」 而忽視 「WORD-8」

例如

A123-300 would be type=A123, series=300 
A123-300/WORD-8 would be type=A123, series=300 
A123/A456 would be type=A123, type=A456 
WORD-8/A456-200 would be type=A456, series=200 

到目前爲止,我有這樣的事情:

WITH gen AS 
    (select 'A123-700' x from dual 
    UNION ALL 
    select 'A123-700/WORD-8' x from dual 
    union all 
    select 'A123/A456' x from dual 
    union all 
    select 'WORD-8/A456-800' x from dual 
) 
SELECT x , 
    regexp_substr(x, '[^/]+')    as first_slash, 
    regexp_substr(x, '[^-]+')    as first_type, 
    regexp_substr(x, '-\w*')    as first_series, 
    regexp_substr(x, '[^/][^DASH]+', 1, 2) as second_slash, 
    regexp_substr(x, '[^/]+', 1, 2)  as second_type, 
    regexp_substr(x, '-\w+', 1, 2)   as second_series 
FROM gen; 

但結果並不是我所希望的。 我想沒有 - ,而我的「第二」信息也不是正確的。

X     FIRST_SLASH FIRST_TYPE FIRST_SERIES SECOND_SLASH SECOND_TYPE SECOND_SERIES 
A123-700   A123-700 A123  -700   (null)  (null)  (null) 
A123-700/WORD-8 A123-700 A123  -700   D-8   WORD-8  -8 
A123/A456  A123  A123/A456 (null)  A456   A456  (null) 
WORD-8/A456-800 WORD-8  WORD  -8   D-8/  A456-800 -800 

有人能幫我指出正確的方向嗎?

謝謝!

回答

1
WITH 
    gen AS ( 
    select 'A123-700' x from dual 
    UNION ALL 
    select 'A123-700/WORD-8' x from dual 
    union all 
    select 'A123/A456' x from dual 
    union all 
    select 'WORD-8/A456-800' x from dual 
), 
    t_slash as (
    SELECT x , 
     nullif(regexp_replace(x, '\s*/.*$'),'WORD-8') as first_slash, 
     nullif(regexp_replace(x, '^[^/]*/?\s*'),'WORD-8') as second_slash 
    FROM gen 
) 
select x, first_slash, 
    regexp_substr(first_slash, '^[^-]*') as first_type, 
    regexp_replace(first_slash, '^[^-]*-?') as first_series, 
    second_slash, 
    regexp_substr(second_slash, '^[^-]*') as second_type, 
    regexp_replace(second_slash, '^[^-]*-?') as second_series 
from t_slash 

fiddle

+0

真正幫助,謝謝!一個問題,如果它可能是'WORD-8'或'WORD 8'? – froglander

+0

@froglander - 您可以使用任何字符串而不是WORD-8。 –

1
WITH gen AS 
    (select 'A123-700' x from dual 
    UNION ALL 
    select 'A123-700/WORD-8' x from dual 
    union all 
    select 'A123/A456' x from dual 
    union all 
    select 'WORD-8/A456-800' x from dual 
) 
SELECT x , 
    regexp_substr(x,'A[[:alnum:]]+',1) as first_type, 
    NULLIF(regexp_substr(x,'A[[:alnum:]]+',2), 
      regexp_substr(x,'A[[:alnum:]]+',1)) as second_type, 
    regexp_substr(x,'(A[[:alnum:]]+)-([[:digit:]]+)',1) as full, 
    regexp_substr(regexp_substr(x,'(A[[:alnum:]]+)-([[:digit:]]+)',1), 
       '-([[:digit:]]+)', 
       1) as first_series 
FROM gen;