mysql中正则表达式的使用

  mysql中正则表达式的性能要高于like,所以这里总结一下正则表达式的使用。

正则表达式的模式及其含义:

  下面举例说明其用法:

建表student:

create table student(id int(6) auto_increment,name carchar(6),age int(3),primary key(id));
插入数据:
insert into student(name,age) values('xzb',20),('spal',22),('wgc',32);

1.^

select name from student where name REGEXP '^x'; --查询以x开头的数据

2.$

select * from student where name REGEXP 'c$'; --查询以c结尾的数据

3.".":这个字符就是英文下的点,它匹配任何一个字符,包括回车、换行等。

select * from student where name REGEXP 'x..'; --匹配首字母为x,其余字母任意的数据

4.*:星号匹配0个或多个字符,在它之前必须有内容。

select * from student where name REGEXP 'x*'; --匹配任意个字符

5."+":加号匹配1个或多个字符,在它之前也必须有内容。

select * from student where name REGEXP 'x*';--匹配大于1个的任意字符

6."?":问号匹配0次或1次。

select * from student where name REGEXP 'x?';--匹配0个或1个字符

7.xzb|spal|

select * from student where name REGEXP 'xzb|spal';--匹配xzb或spal

8.[x-z]*

select * from student where name REGEXP '^[x-z]';--匹配以x,y,z中的字符开头的数据

select * from student where name REGEXP '[a-d]$';--匹配以a-d中的字符结尾的数据

9.[^x-z]*

select * from student where name REGEXP '^[^x-z]';--匹配不在x-z内的字符开头的数据

select * from student where name REGEXP '[^h-j]$';--匹配不在x-z内的字符开头的数据

10.{n}

select * from student where name REGEXP '^s{2}';--匹配以s开头且重复至少2次的所有数据

11.{n,m}

select * from student where name REGEXP '^s{2,5}';--匹配以s开头且重复2到5次的所有数据

原文地址:https://www.cnblogs.com/confident1012/p/6226796.html