MySql学习笔记(二) —— 正则表达式的使用

前面介绍利用一些关键字搭配相应的SQL语句进行数据库查找过滤,但随着过滤条件的复杂性的增加,where 子句本身的复杂性也会增加。这时我们就可以利用正则表达式来进行匹配查找。

1.基本字符匹配

select * from products where prod_name regexp '1000' order by prod_name; --匹配产品名字中出现1000的字符商品

select * from products where prod_name regexp '.000' order by prod_name; -- . 表示匹配任意字符,语句也就表示匹配以 000 结尾的任意字符

2.进行or匹配

select * from products where prod_name regexp '1000|2000' order by prod_name; --匹配商品名称包含1000或者2000的商品信息

3.匹配几个字符之一

select * from products where prod_name regexp [123] ton order by prod_name; --[123]表示定义的一组字符,匹配名字为 1 ton 和 2 ton 

4.匹配范围

select * from products where prod_name regexp [1-9] ton order by prod_name; --[1-9]表示定义的一组字符匹配范围,表示匹配1到9 

5.匹配特殊字符

select * from products where prod_name regexp '\.' order by prod_name; --在正则表达式中 . 表示匹配任意字符,有特殊含义,我们在匹配时要用\转义一下。

其他也需要转义的元素:

\f 换页; \n换行; \r回车; \t制表; \v 纵向制表

6.匹配多个实例

select prod_name from products where prod_name regexp '\([0-9] sticks?\)' order by prod_name;  --\( 表示匹配 (,[0-9] 表示匹配任意字符 ?表示匹配0个或1个字符

* : 匹配0个或多个字符

+ :匹配1个或多个字符

? : 匹配0个或1个字符

^ : 文本的开始

$ : 文本的结尾

原文地址:https://www.cnblogs.com/love-Stefanie/p/6892875.html