我會使用舊的SUBSTR而不是REGEXP。由於REGEXP將佔用太多的CPU資源。
您的要求很簡單。
對於數據爲Chapter 18 Unit 10 Sect 16
,如果你想第18章作爲輸出:
只需執行:
Select substr(column, 1, 10) from table
同樣,您可以爲其他輸出做。
編輯:夥計們,你們中的一些人可能會認爲我爲什麼在REGEXP上強調老的SUBSTR。只需追蹤一下,然後查看跟蹤輸出。我同意,對於更新的版本,Oracle已經對REGEXP做了很多改進。但是,直到日期我還沒有看到一個我滿意的情況。我可能是錯的,所以,如果有人有測試用例,我真的很想看到它。這對我們所有人來說都是一次很好的學習。
更新顯示關於REGULAR EXPRESSION的上述測試用例比SUBSTR + INSTR更快,是錯誤的!
正則表達式:
SQL> DECLARE
2 l_start NUMBER := dbms_utility.get_cpu_time;
3 BEGIN
4 FOR i IN (WITH t
5 AS (SELECT 'Chapter '
6 || LEVEL
7 || ' Unit '
8 || LEVEL
9 || ' Sect '
10 || LEVEL d
11 FROM dual
12 CONNECT BY ROWNUM < 100000)
13 SELECT Regexp_substr(d, 'Chapter [0-9]*') chapter,
14 Regexp_substr(d, 'Unit [0-9]*') unit,
15 Regexp_substr(d, 'Sect [0-9]*') sect
16 FROM t) LOOP
17 NULL;
18 END LOOP;
19
20 dbms_output.Put_line('time taken by REGULAR EXPRESSION : '
21 || (dbms_utility.get_cpu_time - l_start)
22 || ' hsec');
23 END;
24
25/
time taken by REGULAR EXPRESSION : 61 hsec
PL/SQL procedure successfully completed.
SUBSTR + INSTR:
SQL> DECLARE
2 l_start NUMBER := dbms_utility.get_cpu_time;
3 BEGIN
4 FOR i IN (WITH t
5 AS (SELECT 'Chapter '
6 || LEVEL
7 || ' Unit '
8 || LEVEL
9 || ' Sect '
10 || LEVEL d
11 FROM dual
12 CONNECT BY ROWNUM < 100000)
13 SELECT Substr(d, 1, Instr(d, ' ', 1, 2) - 1)
14 chapter,
15 Substr(d, Instr(d, ' ', 1, 2),
16 Instr(d, ' ', 1, 4) - Instr(d,
17 ' ', 1, 2))
18 unit,
19 Substr(d, Instr(d, ' ', 1, 4), Length(d) - Instr(d, ' ', 1,
20 4)
21 + 1)
22 sect
23 FROM t) LOOP
24 NULL;
25 END LOOP;
26
27 dbms_output.Put_line('time taken by SUBSTR + INSTR : '
28 || (dbms_utility.get_cpu_time - l_start)
29 || ' hsec');
30 END;
31
32/
time taken by SUBSTR + INSTR : 28 hsec
PL/SQL procedure successfully completed.
因此,它可以清楚地看到SUBSTR + INSTR了不到一半的時間定期表達。
是數字常量?它能成爲「第45章145單元2」嗎?如何區分大小寫? – zaratustra 2014-09-10 14:50:57
你試過了什麼?在stackoverflow上有很多很多類似的問題。 – 2014-09-10 15:19:16