0

I was trying to obtain a string before the penultimate occurrence of '_' character:

For instance:

 LORIK_BB_ID_FF_KKK_HUY_222_44
 LUN_GGG_MAMA_FF_GG_GG_TT22_3

Obtain this part (considering that the string will always have 4 or more underlines and the same amount of underlines for each record):

LORIK_BB_ID_FF_KKK_HUY
LUN_GGG_MAMA_FF_GG_GG

I already tried using:

select SUBSTR('LORIK_BB_ID_FF_KKK_HUY',0, (INSTR ('LORIK_BB_ID_FF_KKK_HUY', '_', -1)) - 1) from dual;

This one seems to obtain every character before the last occurence of '_', I can't seem to find a solution to obtain the characters before the penultimate occurence of underscore.

3 Answers 3

1

underscores might be counted REGEXP_COUNT(str,'_') - 1 times instead of REGEXP_COUNT(str,'_') + 1, which is the number of substrings splitted by underscores, and concatenate all by using LISTAGG(...,'_')... function in order to get the substring upto the penultimate underscore :

WITH t(ID,str) AS
(
 SELECT 1, 'LORIK_BB_ID_FF_KKK_HUY_222_44' FROM dual UNION ALL
 SELECT 2, 'LUN_GGG_MAMA_FF_GG_GG_TT22_3'  FROM dual 
)  
 SELECT ID,
        LISTAGG(REGEXP_SUBSTR(str,'[^_]+',1,level),'_')
        WITHIN GROUP (ORDER BY level) AS "Result String"
   FROM t
CONNECT BY level <= REGEXP_COUNT(str,'_') - 1
    AND PRIOR SYS_GUID() IS NOT NULL
    AND PRIOR ID = ID
  GROUP BY ID;


ID  Result String
--  ----------------------
1   LORIK_BB_ID_FF_KKK_HUY
2   LUN_GGG_MAMA_FF_GG_GG

Demo

Sign up to request clarification or add additional context in comments.

Comments

1

REGEXP_SUBSTR could be used to divide the string into 2 parts using groups. The first group being the string up to but not including the penultimate underscore, the second group being the penultimate underscore and the rest of the line until the end (allowing for any number of characters between the underscores). Return the 1st group.

WITH T(ID,str) AS
(
 SELECT 1, 'LORIK_BB_ID_FF_KKK_HUY_222_44' FROM dual UNION ALL
 SELECT 2, 'LUN_GGG_MAMA_FF_GG_GG_TT22_3'  FROM dual 
)  
SELECT ID,
REGEXP_SUBSTR(str, '(.*)(_.*_.*$)', 1, 1, NULL, 1) mystring
from t;

        ID MYSTRING                     
---------- -----------------------------
         1 LORIK_BB_ID_FF_KKK_HUY       
         2 LUN_GGG_MAMA_FF_GG_GG        

2 rows selected. 

Comments

0

Why you are not trying this:

 select SUBSTR('LUN_GGG_MAMA_FF_GG_GG_TT22_3',0, (INSTR ('LUN_GGG_MAMA_FF_GG_GG_TT22_3', '_', -1, 2)) - 1) from dual;

select SUBSTR('LORIK_BB_ID_FF_KKK_HUY_222_44',0, (INSTR ('LORIK_BB_ID_FF_KKK_HUY_222_44', '_', -1, 2)) - 1) from dual;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.