一、字符串查找函數(shù)? INSTR()
二、字符串截取函數(shù) SUBSTR()
三、實際應(yīng)用: SUBSTR 和 INSTR 結(jié)合使用
一、字符串查找函數(shù)? INSTR()
格式: INSTR(str , substr , 【start_position ,【 nth_appearance】】)?
? ? ? ? ?? @param str:源字符串 ? ??
?????????? @param substr:子字符串,在源字符串中查找的字符串
?????????? @param start_position:從源字符串str開始查找的位置。可選,默認(rèn)為1。正數(shù)時從左向右檢索,負(fù)數(shù)時從右向左檢索
?????????? @param nth_appearance:查找源字符串時,第幾次出現(xiàn)目標(biāo)字符串 str2 。可選,默認(rèn)為1,不能為負(fù)數(shù)。
????? ? ?? @return 返回子字符串在源字符串中出現(xiàn)的位置(沒找到返回0)
注:字符串索引號從1開始,而不是從0開始。
例:(1) INSTR('todayisabeautifulday' , 'to')??
???????????????? 返回結(jié)果:1 (因為字符串索引號從1開始,所以返回1,不是返回0)
??? ? (2)? INSTR('todayisabeautifulday' , 'day',1, 1)
? ? ???????????? 返回結(jié)果: 3 (返回第一次查出 day 的位置)
????? (3) 若改成 INSTR('todayisabeautifulday' , 'day',1, 2)
??????????????? 則返回結(jié)果為第二次出現(xiàn) day 的位置:18
????? (4) INSTR('today is a beautiful day' , 'is',1, 1)
??????????????? 返回結(jié)果:7 (空格也是一個字符)
二、字符串截取函數(shù) SUBSTR()
格式:SUBSTR(str, start_position ,【 length】)
??????????? @param str:? 源字符串 ? ???
??????????? @param start_position: 檢索位置。參數(shù)為正時從左向右檢索,參數(shù)為負(fù)時從右向左檢索
??????????? @param length:將要截取的長度,可選,默認(rèn)從start_position 位開始截取全部。值小于1時返回空字符串?
??????????? @return 返回截取的字符串
注: 字符串索引號從1開始,而不是從0開始。
例:(1)SUBSTR ('ABCDEFG', 2, 3)
??????????????? 返回結(jié)果:'BCD' (從第2個字符開始,截取長度為3的子串)
?????? (2)substr('ABCDEFG',? -2)?
??????????????? 返回結(jié)果:'FG'?? (從倒數(shù)第2個字符開始,截取到源串的末尾)
?????? (3)substr('ABCDEFG', -4, 2)
?????????????? 返回結(jié)果:'DE' (從倒數(shù)第4個字符開始,截取長度為2的子串)
????? (4)substr('ABCDEFG', 4, -1)
?????????????? 返回結(jié)果: 空字符串 (截取長度小于1時,返回空字符串?)
三、實際應(yīng)用: SUBSTR 和 INSTR 結(jié)合使用
結(jié)合 SUBSTR()和 INSTR()來實現(xiàn)截取字符串中特定字符前后的字符串
(1)截取 “hello,world” 字符串中 “,” 分隔符之前的字符串
?SELECT SUBSTR(' hello,world', 1, INSTR('hello,world', ',')-1)? FROM DUAL;
?返回結(jié)果:hello
(2)截取 “hello,world, ye” 字符串中第1次出現(xiàn)的 “,” 字符和第2次出現(xiàn)的 “,” 字符之間的字符串
SELECT SUBSTR('hello,world,ye', INSTR('hello,world,ye', ',',1)+1, INSTR('hello,world,ye', ',', 1, 2)-INSTR('hello,world,ye', ',', 1)-1 ) FROM DUAL;?
返回結(jié)果:world
參考鏈接:https://blog.csdn.net/lanmuhhh2015/article/details/78861614