0

I want to return the following position from the strings using REGEXP_INSTR.

I am looking for the word car with exact match in the following strings.

car,care,oscar - 1
care,car,oscar - 6
oscar,care,car - 12

something like

SELECT REGEXP_INSTR('car,care,oscar', 'car', 1, 1) "REGEXP_INSTR" FROM DUAL;

I am not sure what kind of escape operators to use.

3 Answers 3

2

A simpler solution is to surround the source string and search string with commas and find the position using INSTR.

SELECT INSTR(',' || 'car,care,oscar' || ',', ',car,') "INSTR" FROM DUAL;

Example:

SQL Fiddle

with x(y) as (
SELECT 'car,care,oscar' from dual union all
SELECT 'care,car,oscar' from dual union all
SELECT 'oscar,care,car' from dual union all
SELECT 'car' from dual union all
SELECT 'cart,care,oscar' from dual
)
select y, ',' || y || ',' , instr(',' || y || ',',',car,')
from x


|               Y |       ','||Y||',' | INSTR(','||Y||',',',CAR,') |
|-----------------|-------------------|----------------------------|
|  car,care,oscar |  ,car,care,oscar, |                          1 |
|  care,car,oscar |  ,care,car,oscar, |                          6 |
|  oscar,care,car |  ,oscar,care,car, |                         12 |
|             car |             ,car, |                          1 |
| cart,care,oscar | ,cart,care,oscar, |                          0 |
Sign up to request clarification or add additional context in comments.

Comments

0

The following query handles all scenarios. It returns the starting position if the string begins with car, or the whole string is just car. It returns the starting position + 1 if ,car, is found or if the string ends with ,car to account for the comma.

SELECT 
  CASE
    WHEN REGEXP_LIKE('car,care,oscar', '^car,|^car$') THEN REGEXP_INSTR('car,care,oscar', '^car,|^car$', 1, 1)
    WHEN REGEXP_LIKE('car,care,oscar', ',car,|,car$') THEN REGEXP_INSTR('car,care,oscar', ',car,|,car$', 1, 1)+1
    ELSE 0
  END  "REGEXP_INSTR"
FROM DUAL;

SQL Fiddle demo with the various possibilities

Comments

0

I like Noel his answer as it gives a very good performance! Another way around is by creating separate rows from a character separated string: pm.nodes = 'a;b;c;d;e;f;g'

(select regexp_substr(pm.nodes,'[^;]+', 1, level) 
   from dual 
connect by regexp_substr(pm.nodes, '[^;]+', 1, level) is not null)

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.