MySQL必知必会》正则表达式

《MySQL必知必会》正则表达式

正则表达式

1.1、关键字 REGEXP

正则表达式的使用需要用到关键字 REGEXP

select prod_name
from products
where prod_name regexp '1000';

image-20200822211126660

从效果看和关键字 LIKE 有相似之处。但只从这个例子中看不出差别,而且使用正则表达式还会降低性能。

但是如果用 LIKE 替换上面的句子,是查询不到数据的。

因为 LIKE 是匹配整个列内的全文本才会返回数据,要想做到和 REGEXP 一样的效果,要使用通配符或者拼接函数才行。


正则表达式是需要配合起来使用才能看到它的扩展性。

select prod_name
from products
where prod_name regexp '.000';

image-20200822210806178

. 在正则表达式中表示任意一个字符。

以上例子使用的是数字匹配,要知道 MySQL 3.23.4+ 正则表达式匹配都是不区分大小写的。

1.2、OR 匹配 ‘ | ’

select prod_name
from products
where prod_name regexp 'ton|1000|2000';

image-20200822212051907

使用 | 可以起到 or 的作用,要注意,不要有多余的空格,将会影响匹配。可以给出两个或两个以上的条件。

1.3、匹配几个字符之一

select prod_name
from products
where prod_name regexp '[125] ton';

image-20200822212503011

用 [ ] 定义一组字符,以上的例子表示匹配 1 2 5 三个字符。注意 ton 前是有一个空格的。匹配的是 ‘1 ton’ , ‘2 ton’ ,’5 ton’ 这三个字符串。

还有一种写法,是使用 |

select prod_name
from products
where prod_name regexp '[1|2|5] ton';

得到的结果是和上面的一样的。

但是要注意,下面这样写是得不到预期结果的。

select prod_name
from products
where prod_name regexp '1|2|5 ton';

image-20200822213311682

因为上面写法告诉 MySQL ,将匹配 1 , 2 ,5 ton 单个字符串

此外,还可以使用 ^ 来匹配这些字符以外的列。

select prod_name
from products
where prod_name regexp '[^123]';

image-20200822213614258

^ 当然也是不能匹配 NULL 值的列的。

1.4、匹配范围

select prod_name
from products
where prod_name regexp '[1-5] ton';

image-20200822214049875

‘ – ‘ 表示范围,1-5,表示1、2、3、4、5 。

a-z 表示任意字母范围。

1.5、特殊字符

上面提到 . 表示任意一个字符,那么如果需要匹配 ‘.’ 要怎么才能让MySQL知道不去转义它?

答案是 反斜杆 \ 。

select prod_name
from products
where prod_name regexp '\\.';

image-20200822215703347

还可以引用元字符:

元字符 说明
\\f 换页
\\n 换行
\\r 回车
\\t 制表
\\v 纵向制表

匹配 \ 需要 \\\ 来表示。

1.6、匹配字符类

image-20200822220359075

1.7、匹配多个实例

select prod_name
from products
where prod_name regexp '\\([1-5] sticks?\\)';

image-20200823120856066

\\( :匹配 ( ;\\) :匹配 )

[1-5] : 匹配数字 1 -5 的范围;

sticks? :需要拆分为 stick 和 s? 来看待,stick :匹配全文

s? : 表示 ? 前面的 s 为匹配0或1个,即为可选。

重复元字符说明如下表:

image-20200823121356180

结合上表匹配字符类的元字符,还可以

select prod_name
from products
where prod_name regexp '[[:digit:]]{4}';

image-20200822210806178

[:digit:] :表示匹配任意数字 ,{4} : 表示出现四次。

当然还可以有其他写法,如下:

select prod_name
from products
where prod_name regexp '[0-9][0-9][0-9][0-9]';

1.8、定位符

定位元字符说明如下:

image-20200823122116098

想找以任意数字作为开头的产品名:

select prod_name
from products
where prod_name regexp '^[1-9]';

image-20200823122359073

想找以任意数字作为结尾的产品名:

select prod_name
from products
where prod_name regexp '[0-9]$';

image-20200822210806178

注意 ^ 的两种用法

用在[ ] 内表示否定该集合,用在 [ ] 外表示文本的开始处。