mysql中正則表達式的性能要高於like,所以這里總結一下正則表達式的使用。
正則表達式的模式及其含義:
下面舉例說明其用法:
建表student:
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次的所有數據
