Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Is there a REGEXP_SUBSTR alternative for my SUBSTR(...INSTR...)?

BoneistAug 9 2011 — edited Aug 9 2011
Hi,

I've got a column that can contain up to 3 parts:

1. anything up to the first underscore
2. anything between the first and second underscore (if there isn't a second underscore, then it's from the first underscore to the end of the string)
3. anything after the third underscore, which could include other underscores.

The first two parts are easy to do, but I've struggled to find a REGEXP_SUBSTR way of doing the third part, and have ended up with a clunky substr / instr combo. Is there a better way?
with sd as (select 'abcd_1234' str from dual union all
            select 'abcd_1234_1' str from dual union all
            select 'abcd_1234_efg_1' str from dual union all
            select 'abcd_1234_efg_hij_2' str from dual)
select str,
       REGEXP_SUBSTR(str, '[^_]+', 1, 1) str_1,
       REGEXP_SUBSTR(str, '[^_]+', 1, 2) str_2,
       SUBSTR(str, DECODE(INSTR(str, '_', 1, 2), 0, NULL, INSTR(str, '_', 1, 2) + 1)) str_3
from   sd;

STR                 STR_1               STR_2               STR_3              
------------------- ------------------- ------------------- -------------------
abcd_1234           abcd                1234                                   
abcd_1234_1         abcd                1234                1                  
abcd_1234_efg_1     abcd                1234                efg_1              
abcd_1234_efg_hij_2 abcd                1234                efg_hij_2          
TIA!

ETA: I'm on 10.2.0.4

Edited by: Boneist on 09-Aug-2011 17:30
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 6 2011
Added on Aug 9 2011
1 comment
1,994 views