Oracle 中 substr 和 instr 函数简单用法
磊磊

Oracle 的 substr 和 instr 函数简单用法

substr 函数简单用法

substr 介绍

/*

* 截取字符串(字符串位置从 1 开始,而不是从 0 开始)

* @param string 源字符串

* @param position 检索位置,参数为正时,从左向右检索,参数为负时,从右向左检索

* @param substring_length 要截取的长度,可省略(默认从 position 位开始截取全部), 值小于 1 时返回空字符串

* @return 返回截取的字符串

*/

substr(string, position, substring_length);

测试代码

1
2
3
4
5
select substr('Hello World', 0, 1)  c1-- 返回结果为 'H'  * 从字符串第一个字符开始截取长度为 1 的字符串
, substr('Hello World', 1, 1) c2-- 返回结果为 'H' *0 和 1 都是表示截取的开始位置为第一个字符
, substr('Hello World', 2, 4) c3-- 返回结果为 'ello'
, substr('Hello World', -3, 3) c4-- 返回结果为 'rld' * 负数 (-i) 表示截取的开始位置为字符串右端向左数第 i 个
from PRPDKIND;

测试图片

image


instr 函数的简单用法

instr 函数介绍:

/*

* 返回子字符串在源字符串中的位置(字符串位置从 1 开始,而不是从 0 开始)

* @param string 源字符串

* @param substring 子字符串

* @param position 检索位置,可省略(默认为 1), 参数为正时,从左向右检索,参数为负时,从右向左检索

* @param occurrence 检索子字符串出现的次数,可省略(默认为 1), 值只能为正整数,否则会报错

* @return 返回子字符串在源字符串中出现的位置(没找到返回 0)

*/

instr(string, substring, position, occurrence)

测试代码

1
2
3
4
5
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

测试图片

image

总结

  • 可以将 SUBSTR 和 INSTR 结合使用来实现截取字符串中特定字符前后的字符串
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
-- 截取“hello,world”字符串中“,”分隔符之前的字符串
SELECT SUBSTR('hello,world', 1, INSTR('hello,world', ',')-1) FROM DUAL;
SELECT SUBSTR('hello,world', 0, INSTR('hello,world', ',')-1) FROM DUAL;
-- 结果:hello

-- 截取“hello,world”字符串中“,”分隔符之后的字符串
SELECT SUBSTR('hello,world', INSTR('hello,world', ',')+1) FROM DUAL;
-- 结果:world

-- 截取“hello,world,HH”字符串中第 1 次出现的“,”字符和第 2 次出现的“,”字符之间的字符串
SELECT SUBSTR('hello,world,HH', INSTR('hello,world,HH', ',',1)+1, INSTR('hello,world,HH', ',', 2)-1) FROM DUAL;
-- 结果:world


SELECT SUBSTR('hello,world', 1, INSTR('hello,world', ',') - 1) C1,-- 结果:hello
SUBSTR('hello,world', 0, INSTR('hello,world', ',') - 1) C2,-- 结果:hello
SUBSTR('hello,world', INSTR('hello,world', ',') + 1) C3,-- 结果:world
SUBSTR('hello,world,HH', INSTR('hello,world,HH', ',', 1) + 1, INSTR('hello,world,HH', ',', 2) - 1) C4
-- 截取“hello,world,HH”字符串中第 1 次出现的“,”字符和第 2 次出现的“,”字符之间的字符串 -- 结果:world
FROM DUAL;

实例图片

image

由 Hexo 驱动 & 主题 Keep
访客数 访问量