基础用法:
- 去除指定字符串前后的空格
select trim(' hello caicai ')trim from dual;--当不加别名时,显示字符串右边还是有空格。
2.去除指定字符串左右的空格
select ltrim(' hello caicai ')ltrim from dual;--左
select rtrim(' hello caicai ')rtrim from dual;--右
进阶用法:
接收其他参数来去除指定字符串左、右及其两边的字符。
该处的进阶用法不仅可以去除半角空格,也可以去除全角空格,而基础的trim用法只可以去除半角空格。
- 截取集为一个字符的情况(注意:此处截取集只能为一个字符,否则报错)
select trim(leading ' ' from ' hello caicai ') leadingtrim from dual;
select trim(trailing ' ' from ' hello caicai ') trailingtrim from dual;
select trim(both ' ' from ' hello caicai ') bothtrim from dual;
select trim(leading 'y' from 'ya hello caicai y') leadingtrim from dual;
select trim(trailing 'y' from 'ya hello caicai y') trailingtrim from dual;
select trim(both 'y' from 'ya hello caicai y') bothtrim from dual;
不加关键词leading,trailing,both,其用法相当于trim的基础用法。
select trim( 'y' from 'ya hello caicai y') leadingtrim from dual;
2.截取集为多个字符的情况:
ltrim(string1,string2),rtrim(string1,string2)
ltrim(string1,string2):从字符串string1左侧开始去除与string2字符集合中单个字符匹配的字符,直到在string1中遇上某个字符,该字符不在string2字符集合中。
简单来说就是,将string2中的每个字符与string1左侧开始的每个字符匹配,若相同,则继续匹配,若不同则返回其字符及其剩下的字符。
select ltrim('abcbcaxcba','abc') ltrim from dual;
rtrim(string1,string2):从字符串string1右侧开始去除与string2字符集合中单个字符匹配的字符,直到在string1中遇上某个字符,该字符不在string2字符集合中。
简单来说就是,将string2中的每个字符与string1右侧开始的每个字符匹配,若相同,则继续匹配,若不同则返回其字符及其剩下的字符。
select rtrim('abcbcaxcba','abc') rtrim from dual;
注意:
在使用trim,ltrim,rtrim的进阶用法时,空格对应空客,空串对应空串,否则会获取不到自己想要的结果。注意空格与空字符串,空格指引号中有一个空格,空字符串指引号间啥也没有。
如:
空格 空串
SELECT ltrim(' abcbcaxcba','') rtrim FROM dual;
空格 空格
SELECT ltrim(' abcbcaxcba',' ') rtrim FROM dual;
如果你对该知识点感兴趣,可点击链接了解详情。