MySQL数据库中的正则表达式

本文通过对MySQL数据库中的部分正则表达式进行使用测试
首先观察一下我们本次使用的数据库中有哪些内容

select * from test;

字段名为“name”

xxxx 1000
xxxx 2000
1 point 5
2 point 5
.5 point 5
apple (3 tons)
apple (1 ton)
nothing serious

基本字符匹配 通过’ '搜索对应的数据

输入的代码:

select name from test where name regexp '000';

结果:

xxxx 1000
xxxx 2000

首先我们的正则表达式使用的是 regexp 来标识的
通过单引号,向对应数据集中搜索含有单引号中字符的数据。

我们还可以通过“.”来代替任意一个字符来搜索:

select name from test where name regexp '.000';
xxxx 1000
xxxx 2000

可以发现结果是一样的

进行类似于or的匹配

代码:

select name from test where name regexp '1000|2000';

结果:

xxxx 1000
xxxx 2000

“ | ”实际上和“或”也就是“or”意思相同,这一行代码和用or语句连接起来其实是一样的

匹配字符的一部分

代码:

select name from test where name regexp '[12345] point';

结果:

1 point 5
2 point 5
.5 point 5

取出[]中任意字符使得单引号中的数据在整个数据集合中一旦存在,那么这个数据就能查询得到。
事实上[12345]是[1|2|3|4|5]的缩写,使用后者可以得到一样的结果

代码:

select name from test where name regexp '[1|2|3|4|5] point';

结果:

1 point 5
2 point 5
.5 point 5

我们不添加中括号试一试:

select name from test where name regexp '1|2|3|4|5 point';
xxxx 1000
xxxx 2000
1 point 5
2 point 5
.5 point 5
apple (3 tons)
apple (1 ton)

我们发现他会得到更多的数据
实际上这段代码寻找到的内容是含有1或者2或者3或者4或者5 point的数据
这是关于中括号的使用

匹配一个范围

[0-9][a-z][A-Z]都是范围的表示 上一个例子我们也可以通过匹配’[1-5] point‘得到
代码:

select name from test where name regexp '[1-5] point';

结果:

1 point 5
2 point 5
.5 point 5

匹配特殊字符

之前我们了解到’.‘可以代表任意一个字符,那如果我们需要搜索的数据中有’.‘那应该怎么搜索呢?
代码:

select name from test where name regexp '.';

结果:

xxxx 1000
xxxx 2000
1 point 5
2 point 5
.5 point 5
apple (3 tons)
apple (1 ton)
nothing serious

直接搜索会得到所有的数据
我们需要使用\来寻找特殊字符

代码:

select name from test where name regexp '\\.';

结果:

.5 point 5

一些元字符

元字符

说明

\\f

换页

\\n

换行

\\r

回车

\\t

制表

\\v

纵向制表

匹配字符类以及多个实例

有这样一个字符类表供我们平时使用


说明

[:alnum:]

任意字母和数字(同[0-9a-zA-Z]相同)

[:alpha:]

任意字符(同[a-zA-Z])

[:blank:]

空格和制表

[:cntrl:]

ASCII控制字符(ASCII 0到31和127)

[:digit:]

任意数字(同[0-9])

[:graph:]

与 [:print:]相同,但是不包括空格

[:lower:]

任意小写字母(同[a-z])

[:print:]

任意可打印字符

[:punct:]

既不在[:alnum:]又不在[:cntrl:]中的任意字符

[:space:]

包括空格在内的任意空白字符

[:upper:]

任意大写字母(同[A-Z])

[:xdigit:]

任意十六进制数字(同[a-fA-F0-9])

有些时候我们匹配的可能不止一个,在需要多个对应类字符时有这样一些方式可以使用:

元字符

说明

*

0个或者多个匹配

+

1个或者多个匹配


0个或者1个

{n}

指定数目的匹配

{n,}

不少于指定数目的匹配

{n,m}

匹配数目的范围(m小于255)

举例:
代码:

select name from test where name regexp '\\([0-9] tons?\\)';

结果:

apple (3 tons)
apple (1 ton)

代码:

select name from test where name regexp '[[:digit:]]{4}';

结果:

xxxx 1000
xxxx 2000

匹配定位元字符

通过限制字符存在的位置进一步提高了搜索的效率

元字符

说明

^

文本的开始

$

文本的结尾

[[:<:]]

词的开始

[[:>:]]

词的结尾

举例:
寻找第一个字符位数字或者“.”的数据
代码:

select name from test where name regexp '^[0-9\\.]';

结果

1 point 5
2 point 5
.5 point 5

代码:

select name from test where name regexp '[[:<:]]tons?';

结果:

apple (3 tons)
apple (1 ton)