Oracle instr与substr的区别及用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40931184/article/details/84883231

一、instr函数是一个字符串处理函数,它在Oracle/PLSQL中是返回子字符串在源字符串中的位置。
/*
 * 返回子字符串在源字符串中的位置(字符串位置从1开始,而不是从0开始)
 * @param string 源字符串
 * @param substring 子字符串
 * @param position 检索位置,可省略(默认为1),参数为正时,从左向右检索,参数为负时,从右向左检索
 * @param occurrence 检索子字符串出现的次数,可省略(默认为1),值只能为正整数,否则会报错
 * @return 返回子字符串在源字符串中出现的位置(没找到返回0)
 */
instr(string, substring, position, occurrence);
SELECT INSTR('hello world', 'l') FROM DUAL;           --结果:3
SELECT INSTR('hello world', 'l', 5) FROM DUAL;        --结果:10
SELECT INSTR('hello world', 'l', -1) FROM DUAL;       --结果:10
SELECT INSTR('hello world', 'l', 2, 2) FROM DUAL;     --结果:4
SELECT INSTR('hello world', 'l', -3, 3) FROM DUAL;    --结果:0

注:这一块的第2、3不太透彻
二、substr函数是一个字符串截取函数,它返回的是截取的字符串。
--函数定义如下:
/*
 * 截取字符串(字符串位置从1开始,而不是从0开始)
 * @param string 源字符串
 * @param position 检索位置,参数为正时,从左向右检索,参数为负时,从右向左检索
 * @param substring_length 要截取的长度,可省略(默认从position位开始截取全部),值小于1时返回空字符串
 * @return 返回截取的字符串
 */
substr(string, position, substring_length);
SELECT SUBSTR('hello world', 2) FROM DUAL;        --结果:ello world
SELECT SUBSTR('hello world', -2) FROM DUAL;       --结果:ld
SELECT SUBSTR('hello world', 4, 4) FROM DUAL;     --结果:lo w
SELECT SUBSTR('hello world', -4, 3) FROM DUAL;    --结果:orl
SELECT SUBSTR('hello world', 4, -1) FROM DUAL;    --结果:空字符串

--可以将SUBSTR和INSTR结合使用来实现截取字符串中特定字符前后的字符串
--<1> 截取“hello,world”字符串中“,”分隔符之前的字符串
select INSTR('hello,world', ',')-1 from dual;
SELECT SUBSTR('hello,world', 1, INSTR('hello,world', ',')-1) FROM DUAL;
--结果:hello
--<2> 截取“hello,world”字符串中“,”分隔符之后的字符串  
select INSTR('hello,world', ',')+1 from dual;                           
SELECT SUBSTR('hello,world', INSTR('hello,world', ',')+1) FROM DUAL;
--结果:world
--<3> 截取“hello,world,HH”字符串中第1次出现的“,”字符和第2次出现的“,”字符之间的字符串
select INSTR('hello,world,HH', ',',1)+1,INSTR('hello,world,HH', ',', 2)-1 from dual;
SELECT SUBSTR('hello,world,HH', INSTR('hello,world,HH', ',',1)+1, INSTR('hello,world,HH', ',', 2)-1) FROM DUAL;
--结果:world
三、再给大家几个比较实用的例子
--1、根据文件路径截取文件名;如 E:/1234/5678/1357.txt
--思路:获取文件名,根据/进行划分,从后往前,语法带入:instr(路径,'/',-1)
select INSTR('E:/1234/5678/1357.txt','/',-1)+1 from dual;
select SUBSTR('E:/1234/5678/1357.txt',INSTR('E:/1234/5678/1357.txt','/',-1)+1) from dual;
--2、根据文件名获取文件后缀;如 测试文件.pdf
select SUBSTR('测试文件.pdf',instr('测试文件.pdf','.',1)+1) from dual;
--3、根据去掉文件名后缀;如 测试文件.xls
select SUBSTR('测试文件.pdf',1,instr('测试文件.pdf','.',1)-1) from dual;
--4、根据文件路径获取文件名称,不带后缀
select SUBSTR(SUBSTR('E:/1234/5678/1357.txt',INSTR('E:/1234/5678/1357.txt','/',-1)+1),1,
INSTR(SUBSTR('E:/1234/5678/1357.txt',INSTR('E:/1234/5678/1357.txt','/',-1)+1),'.',-1)-1)from dual;

猜你喜欢

转载自blog.csdn.net/weixin_40931184/article/details/84883231
今日推荐