3

I have below sample values in a column

Abc-123-xyz
Def-456-uvw
Ghi-879-rst-123
Jkl-abc

Expected output is the third element split by '-', in case there is no third element, the last element will be retrieve.

See expected output below:

Xyz
Uvw
Rst
Abc

Thanks ahead for the help.

3
  • 1
    Welcome to Stack Overflow. You can format source code and data samples with the Code Sample {} toolbar button. I've done it for you this time. Commented Jul 30, 2013 at 8:12
  • its not regex_substr in your question title, oracle have regexp_substr Commented Jul 30, 2013 at 8:24
  • Thank you all for the edit. will improve next in my question. Commented Aug 1, 2013 at 3:06

4 Answers 4

2
SELECT initcap(nvl(regexp_substr(word, '[^-]+', 1,3),regexp_substr(word, '[^-]+', 1,2)))  FROM your_table;
Sign up to request clarification or add additional context in comments.

Comments

2

Another approach:

SQL> with t1(col) as(
  2    select 'Abc-123-xyz'     from dual union all
  3    select 'Def-456-uvw'     from dual union all
  4    select 'Ghi-879-rst-123' from dual union all
  5    select 'Jkl-Abc'         from dual
  6  )
  7  select regexp_substr( col
  8                      , '[^-]+'
  9                      , 1
 10                      , case
 11                           when regexp_count(col, '[^-]+') >= 3
 12                           then 3
 13                           else regexp_count(col, '[^-]+')
 14                        end
 15                      ) as res
 16    from t1
 17  ;

Result:

RES
---------------
xyz
uvw
rst
Abc

1 Comment

Just to note that REGEXP_COUNT() was only introduced in 11g (the other regex functions were available in 10g)
2
regexp_substr(column, '(.*?-){0,2}([^-]+)', 1, 1, '', 2)

Comments

0

You can also do it without RegEx:

with t1 as(
  select 'Abc-123-xyz' as MyText     from dual union all
  select 'Def-456-uvw'     from dual union all
  select 'Ghi-879-rst-123' from dual union all
  select 'Jkl-Abc'         from dual
)
SELECT 
  SUBSTR(t1.mytext, LENGTH(t1.mytext) - INSTR(REVERSE(t1.mytext), '-') + 2) 
FROM t1
;

1 Comment

^ true, my fault, I thought he always wanted to get the last triple of characters...

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.