oracle-字符串

就像池昌旭在the k2中说的一句话一样,战争久了,人们便忘记了战争的理由。数据库是用来做啥的呢,存储数据,为何不能用文本来存取?当然可以了,而且linux中还有那么多的文本处理工具,awk,sed,grep,tr,xargs等,都挺好用,但是却没有数据库处理的速度快,格式也没有那么规范。所以需要数据库啊,而且数据库用起来很方便。

那么对数据的存取就是一个基础了,今天主要记录一下,从数据库中取出想要的字符串。

substr+instr找出所需字段子串

substr(char,position,length)

根据长度找字符串。指定字符串,开始位置,长度就可以了,但是实际的数据操作中,往往都不是这么简单的,比如说要取的那个字段为ip:端口,那么ip长度不定。所以需要下面这个函数帮助

instr(string,substring,position,occurrence)

根据字符串找位置。指定字符串,需要查找的子字符串,开始位置,重复出现的次数。就能找到字符串所在的位置。

1
2
3
4
ip_addr
10.25.18.11:123
10.5.18.23:23
10.45.130.234:245

需要取出所有的ip,由于冒号的位置不定,所以需要instr()函数去找出位置。

1
select substr(ip_addr,0,instr(ip_addr,':',0,1)-1) as ip from sometable;

正则的加入

正则匹配后面有许多参数,这些参数是可选的,不一定都要写,但是如果需要后面的参数,那么前面的参数必须都要写。

上面的substrinstr搭配起来用感觉已经很强了,但是这还不能满足苛刻的查找条件,那么正则表达式就可以做到这一切,至于regular expression如何强大就不需要说了。

1
2
3
4
5
6
7
--返回搜索的字符串自身
regexp_substr(source_char,pattern,position,occurrence,return_param,subexpr)
--返回搜索的字符串位置
regexp_instr(source_char,pattern,position,occurrence,return_param,subexpr)
--return_param含义:
--返回匹配字符串的开头0
--返回匹配字符串的开头结尾1

regexp_like正则模糊匹配

现在需要查询出今天6点到14点的数据的和。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
regexp_like(source_char,pattern,match_param)
--不用正则的写法
select sum(money)
from sometable
where to_char(time,'yyyymmddhh24')='2019091606';
select sum(money)
from sometable
where to_char(time,'yyyymmddhh24')='2019091607';
select sum(money)
from sometable
where to_char(time,'yyyymmddhh24')='2019091608';
--....等等等等。然后把结果加起来

--用正则来匹配
select sum(money)
from sometable
where regexp_like(to_char(time,'yyyymmddhh24'),'201909160[6-9] | 1[0-4]');
1
2
3
4
5
6
7
8
9
10
--match_param参数含义:
'i' specifies case-insensitive matching.

'c' specifies case-sensitive matching.

'n' allows the period (.), which is the match-any-character character, to match the newline character. If you omit this parameter, then the period does not match the newline character.

'm' treats the source string as multiple lines. Oracle interprets the caret ( ^) and dollar sign ($) as the start and end, respectively, of any line anywhere in the source string, rather than only at the start or end of the entire source string. If you omit this parameter, then Oracle treats the source string as a single line.

'x' ignores whitespace characters. By default, whitespace characters match themselves.

regexp_count`正则计算出现次数

是对regexp_instr的一个完善,可以计算指定字符出现了多少次

1
2
3
4
5
6
7
regexp_count(source_char,pattern,position,match_param)
--计算123出现次数
SELECT REGEXP_COUNT('123123123123', '123', 3, 'i') COUNT FROM DUAL;

COUNT
----------
3

字符串拼接

1
2
3
4
ip
10.25.18.11
10.5.18.23
10.45.130.234

有时不仅仅是需要取出来数据,还需要加上一些字符串进去。比如说我需要将以上ip插入到一个表中间去。那我是不是需要写许多的insert语句,然后将以上ip带入进去。其实可以用字符串拼接出我们需要的语句:

1
2
3
4
5
select 'insert into sometable values=('''|| ip ||''');' from sometable;
--查询出来的结果就是
insert into sometalbe values=('10.25.18.11');
insert into sometalbe values=('10.5.18.23');
insert into sometalbe values=('10.45.130.234');