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次的所有數據

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM