Search code examples
oracle10g

Get the text between two special characters in oracle


I have a requirement wherein I have to take in the data between two special characters only. The first one and the second character.

Ex: KVN REG#HENDRI#AEP: 6256765058812#KERG00101258#875303069817#THT914000

Here I need the data between first # and the second one. I gathered data from different sources and wrote a query. I just want to know a simpler form of the query, wherein I need not to have to put the rownum function.

Query:

select b.name as v_custname
  from ( select a.*, rownum rnum
           from (SELECT regexp_substr(token, '[^:]+', 1, 1) name
FROM (
  SELECT regexp_substr(s, '[^\#]+', 1, lvl) token, lvl
  FROM (
    SELECT s, LEVEL lvl FROM (select 'KVN REG#HENDRI#AEP: 6256765058812#KERG00101258#875303069817#THT914000' s from dual) 
    CONNECT BY LEVEL < LENGTH(s) - LENGTH(REPLACE(s, '#'))
  )
) ) a
          where rownum <= 2 ) b
 where rnum >= 2;

Solution

  • You can do this with just instr and substr():

    with sample_data as (
      select 'KVN REG#HENDRI#AEP: 6256765058812#KERG00101258#875303069817#THT914000' as token
      from dual
    )
    select substr(token, 
                  instr(token, '#') + 1, 
                  instr(token, '#', 1, 2) - instr(token, '#') - 1
    

    ) from sample_data

    • instr(token, '#') + 1 finds the first occurrence of #
    • instr(token, '#', 1, 2) finds the second occurrence of #
    • substr() takes the first position plus a length to be extracted. The length you need is the second position minus the first position.