2012-11-20 46 views
0
SELECT REGEXP_SUBSTR('one,two,three',',[^,]+') AS reg_result FROM DUAL; 

REG_RESULT  
,two   

SELECT REGEXP_SUBSTR('eight,nineteen,five',',[^,]+') AS reg_result FROM DUAL; 

REG_RESULT  
,nineteen 

我必須從結果中刪除「,」。另外我希望最後的字符串 作爲輸出。即來自'一,二,三'的三個 & 五個從'八,十九,五'。 我該怎麼做?REGEXP_SUBSTR所需輸出

回答

1

如果想只得到了最後一個字,不檢查,如果你的字符串是否符合特定的模式:

SQL> with t1 as(
    2 select 'one,two,three' as str from dual 
    3 ) 
    4 select regexp_substr(str, '([[:alpha:]]+)$') last_word 
    5 from t1 
    6 ; 

LAST_WORD 
--------- 
three 

迴應評論

如何從第一個得到字符串兩個&從第二個十九個?

regexp_substr函數的第四個參數是模式的出現。因此,要獲得字符串中的第二個字,我們可以使用regexp_substr(str, '[^,]+', 1, 2)

SQL> with t1 as(
    2  select 'one,two,three' as str from dual 
    3  ) 
    4 select regexp_substr(str, '[^,]+', 1, 2) as Second_Word 
    5  from t1; 

Second_Word 
--------- 
two 

如果有需要從你的字符串中提取的每一個字:

-- sample of data from your question 
SQL> with t1 as(
    2  select 'one,two,three' as str from dual union all 
    3  select 'eight,nineteen,five' from dual 
    4 ), -- occurrences of the pattern 
    5 occurrence as(
    6 select level as ps 
    7  from (select max(regexp_count(str, '[^,]+')) mx 
    8    from t1 
    9   ) s 
10 connect by level <= s.mx 
11 ) -- the query 
12 select str 
13  , regexp_substr(str, '[^,]+', 1, o.ps) word 
14  , o.ps as word_num 
15 from t1 t 
16  cross join occurrence o 
17 order by str 
18 ; 

STR     WORD   WORD_NUM 
------------------- ----------- ---------- 
eight,nineteen,five eight    1 
eight,nineteen,five nineteen    2 
eight,nineteen,five five     3 
one,two,three  three    3 
one,two,three  one     1 
one,two,three  two     2 

6 rows selected 
+0

感謝您的答覆。如何從第一個** **第二個** **從第二個** **兩** – sam

+0

@sam我已經更新了答案。 –

0
SELECT REGEXP_SUBSTR(REGEXP_SUBSTR('one,two,three',',[^,]+$'),'[^,]+') AS reg_result FROM DUAL; 

我不能肯定,如果Oracle有lookbehinds,但你可以試試這個還有:

SELECT REGEXP_SUBSTR('one,two,three','(?<=,)[^,]+$') AS reg_result FROM DUAL; 
+0

'選擇REGEXP_SUBSTR(「一,二,三」 ,'[^,] + $')AS reg_result FROM DUAL; REG_RESULT three'移除第一個逗號。感謝您的答覆。我的第一個查詢呢? – sam

+0

@sam我發佈的答案解決了這兩個問題。看到這個演示:http://sqlfiddle.com/#!4/d41d8/4497/0 –