Regex INSTR -Snowflake

Viewed 335

I have a question related to a snowflake query:

Oracle query:

INSTR(CFileName, '/', -1) + 1)

Snowflake query

regexp_instr(CFileName, '/', -1) + 1

But when I run this in the Snowflake environment, I get this error:

Invalid parameter value: -3. Reason: Position must be positive

Can you please tell me how to read this below code? And how the output logic?

select regexp_instr('ygzff/afzfzh/yfzdaf/yftfrxdff/aa/ff', '/',3)+1

The answer for above is 7 in snowflake. how sf calculate the answer?

1 Answers
select 
    'ygzff/afzfzh/yfzdaf/yftfrxdff/aa/ff' as input,
    regexp_instr(input, '/',1) as r1,
    regexp_instr(input, '/',2) as r2,
    regexp_instr(input, '/',3) as r3,
    r3+1;

gives:

INPUT R1 R2 R3 R3+1
ygzff/afzfzh/yfzdaf/yftfrxdff/aa/ff 6 6 6 7

the 1,2,3 in my example are the start offset, and result is 1 based offset the / which is the 6. thus the answer 7

The Oracle INSTR position -1 is saying count from the end, and thus is returning the position after the last instance of '/'

we can flip the string around, to find the tail, then minus if the token was found, and then use that like:

select 
    'ygzff/afzfzh/yfzdaf/yftfrxdff/aa/ff' as input,
    length(input) as l,
    regexp_instr(reverse(input), '/') as r,
    iff(r=0,0,l-(r-2)) as tp,
    substr(input, tp) as tail;
INPUT L R TP TAIL
ygzff/afzfzh/yfzdaf/yftfrxdff/aa/ff 35 3 34 ff

or you can also use RIGHT

select 
    column1 as input,
    length(input) as l,
    regexp_instr(reverse(input), '/') as r,
    right(input, iff(r=0,l,r-1))
from values 
    ('ygzff/afzfzh/yfzdaf/yftfrxdff/aa/ff'),
    ('no slashes here');
INPUT L R RIGHT(INPUT, IFF(R=0,L,R-1))
ygzff/afzfzh/yfzdaf/yftfrxdff/aa/ff 35 3 ff
no slashes here 15 0 no slashes here
Related