0

I am stuck here. I am using oracle and I want to get the first part of a string before the first appearance of '|'. This is my query but it returns the last part i.e 25.0. I want it to return first part i.e 53. How do I achieve that?

select regexp_substr('53|100382951130|25.0', '[^|]+$',  1,1) as part1 from dual

1 Answer 1

2

Assuming you always have at least one occurrence of '|', you can use the following, with no regexp:

with test(string) as ( select '53|100382951130|25.0' from dual)    
select substr(string, 1, instr(string, '|')-1)
from test

You could even use regexp to achieve the same thing, or even handle the case in which you have no '|':

with test(string) as (
    select '53|100382951130|25.0' from dual union all
    select '1234567' from dual)    
select string,
       substr(string, 1, instr(string, '|')-1),
       regexp_substr(string, '[^|]*')
from test

You can even handle the case with no occurrence of '|' without regexp:

with test(string) as (
    select '53|100382951130|25.0' from dual union all
    select '1234567' from dual)   
select string,
       substr(string, 1, instr(string, '|')-1),
       regexp_substr(string, '[^|]*'),
       substr(string, 1,
                         case
                           when instr(string, '|') = 0
                             then length(string)
                           else 
                             instr(string, '|')-1
                         end
             )
from test
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much. It sorted me

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.