I would use the old SUBSTR rather than REGEXP. Since REGEXP will take up too much CPU resource.
Your requirement is quite simple.
For data as Chapter 18 Unit 10 Sect 16
, if you want Chapter 18 as output :
Just execute :
Select substr(column, 1, 10) from table
Similarly, you can do for other outputs.
Edit : Folks, some of you might think why am I stressing on good old SUBSTR over REGEXP. Just put trace on, and look at the trace output. I agree, with newer versions, Oracle has made a lot of improvement to REGEXP. But, till date I haven't seen a case where I got satisfied. I might be wrong, so, if anyone has a test case, I would really like to see it. It would a good learning for all of us.
Update to show the above test case about REGULAR EXPRESSION faster than SUBSTR + INSTR, is wrong!
REGULAR EXPRESSION :
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.
So, it can be clearly seen SUBSTR + INSTR took less than half the time that of REGULAR EXPRESSION.