Solved

get string between two characters

Posted on 2013-01-26
3
7,231 Views
Last Modified: 2013-01-26
I need to get part of a string between the first and second underscores. Example: '1234_test_5678'.  Need to get 'test'. I tried regular expressions, but the query would return an error since I also have values with no underscores or with only one underscore.

 select ltrim(REGEXP_SUBSTR('1234_test_5678', '(^[^-]+)|(-[^-]+)',1,
 REGEXP_COUNT('1234_test_5678', '(^[^-]+)|(-[^-]+)')-1),'-') from dual

  select ltrim(REGEXP_SUBSTR('1234 test', '(^[^-]+)|(-[^-]+)',1,
 REGEXP_COUNT('1234 test', '(^[^-]+)|(-[^-]+)')-1),'-') from dual
(ORA-01428: argument '0' is out of range)
0
Comment
Question by:teaone
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 74

Accepted Solution

by:
sdstuber earned 500 total points
ID: 38823408
if your version of Oracle supports subexpressions...

select REGEXP_SUBSTR('1234_test_5678','_([^_]*)_',1,1,null,1) from dual;


if you can't use subexpressions then use trim

select trim(both '_' from REGEXP_SUBSTR('1234_test_5678','_[^_]*_')) from dual;
0
 
LVL 74

Expert Comment

by:sdstuber
ID: 38823416
using the trim method is easier to work with strings that may or may not have underscore delimited content


SELECT  TRIM(BOTH '_' FROM REGEXP_SUBSTR(s, '_[^_]*_|^[^_]*$'))
  FROM (SELECT '1234_test_5678' s FROM DUAL
        UNION ALL
        SELECT '1234 test' FROM DUAL);
0
 

Author Comment

by:teaone
ID: 38823447
excellent, thank you!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Note: this article covers simple compression. Oracle introduced in version 11g release 2 a new feature called Advanced Compression which is not covered here. General principle of Oracle compression Oracle compression is a way of reducing the d…
How to Unravel a Tricky Query Introduction If you browse through the Oracle zones or any of the other database-related zones you'll come across some complicated solutions and sometimes you'll just have to wonder how anyone came up with them.  …
This video explains at a high level with the mandatory Oracle Memory processes are as well as touching on some of the more common optional ones.
This video shows how to Export data from an Oracle database using the Datapump Export Utility.  The corresponding Datapump Import utility is also discussed and demonstrated.

687 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question