2015-08-26 38 views
0

我想在使用Oracle的字符串中找不到分隔符**之後返回NULL值。我有串如何在正則表達式中返回NULL

first path**second path 

我想定界符**後切斷繩子,我用這個正則表達式

REGEXP_SUBSTR(str , '[^**]*$') 

結果是correct.It回報second path。但我需要的是當字符串沒有分隔符**(例如firstpathsecondpath)並且需要返回NULL。我應該改變我的正則表達式?目前,當沒有分隔符**時,正則表達式返回整個字符串。

+1

只是一句話:您的正則表達式不正確 - 它匹配字符串末尾的任何非星號字符序列(您可以用'third * fourth'測試它 - 它會返回'fourth')。 –

+0

@FrankSchmitt不,我已經測試了你說的。它返回NULL –

+0

不,它不會:'從雙'返回'第四''選擇REGEXP_SUBSTR('第三*第四','[^ **] * $')。 –

回答

4

這個查詢將返回NULL,如果兩個星號後跟一些文本沒有在源字符串中發現:

WITH t AS (SELECT 'first path**second path' text FROM DUAL 
      UNION 
      SELECT 'third pathfourth path' text FROM DUAL) 
SELECT SUBSTR(REGEXP_SUBSTR(t.text,'(\*{2})(.+)'),3) 
FROM t 
+0

請注意,'[* * \ *] {2}'相當於'\ * {2}'或'\ * \ *'。 –

+0

完全索尼@AndreaCorbellini。編輯。 – pablomatico

1

當沒有匹配時,您會得到原始字符串。使用select case,測試double-splat。發現時,返回的第二部分,不用時,返回NULL:

SQL> with tbl(rownbr, str) as (
    select 1, 'first path**second path' from dual 
    union 
    select 2, 'third pathfourth path' from dual 
    ) 
    select rownbr, str, case REGEXP_INSTR(str , '\*\*') 
    when 0 then 
     NULL 
    else 
     REGEXP_SUBSTR(str , '[^**]*$') 
     end data 
    from tbl; 

    ROWNBR STR      DATA 
---------- ----------------------- ----------------------- 
     1 first path**second path second path 
     2 third pathfourth path 

SQL>