MySQL 正則表達(dá)式查詢

正則表達(dá)式用來(lái)匹配文本的特殊的串(字符集合)。正則表達(dá)式用正則表達(dá)式語(yǔ)言來(lái)建立,正則表達(dá)式語(yǔ)言是用來(lái)完成匹配特殊的串的一種特殊語(yǔ)言。

Regexp關(guān)鍵字告訴MySQL后面所跟的東西作為正則表達(dá)式處理。
以下使用student、courses、classes表查詢
student表


image.png

courses表


image.png

classes表


image.png

查詢s_name 中有有 ‘王’字的姓名(與like關(guān)鍵字類似)

select s_no,s_sex,s_name from student where s_name REGEXP BINARY '王' order by s_name;
image.png

查詢coursesname中包含H的名字,不區(qū)分大小寫(xiě)

select * from courses s where s.coursesname REGEXP  'H' order by s.coursesname;
image.png

利用關(guān)鍵字REGEXP BINARY 關(guān)鍵字,可以進(jìn)行大小寫(xiě)區(qū)分。

select * from courses s where s.coursesname REGEXP BINARY 'h' order by s.coursesname;
image.png

Regexp 進(jìn)行OR匹配
‘|’ 表示OR操作符,它表示匹配其中之一,因此H和J都匹配并返回
多個(gè)OR條件,可以利用單個(gè)正則表達(dá)式進(jìn)行匹配。

select * from courses s where s.coursesname REGEXP  'H|J' order by s.coursesname;
image.png

Regexp 進(jìn)行特定字符匹配
Regexp 匹配幾個(gè)字符之一,利用 [] 表示、另一種形式的OR

王[麗|紅|艷] == 王麗 或者王紅 或者王艷 為 王[麗|紅|艷] 的縮寫(xiě)

select s_no,s_sex,s_name from student where s_name REGEXP  '王[麗|芳]' order by s_name;
image.png

也可以不帶括號(hào):

select s_no,s_sex,s_name from student where s_name REGEXP  '王|麗|芳' order by s_name;
image.png

Regexp 進(jìn)行范圍匹配
[0-9] 0到9數(shù)字匹配
[a-z] a到z字母匹配

select * from classes s where s.classname REGEXP  'p[A-Z]' order by s.classname;
image.png
select * from classes s where s.classname REGEXP  'py[0-9]' order by s.classname;
image.png

Regexp 進(jìn)行特殊字符匹配
特殊字符匹配,多數(shù)的正則表達(dá)式實(shí)現(xiàn)是使用單個(gè)的反斜杠進(jìn)行轉(zhuǎn)義特殊字符

 select * from classes s where s.classname REGEXP  '\\.' order by s.classname;
image.png

匹配連在一起的3位數(shù)字

 select * from classes s where s.classname REGEXP  '[[:digit:]]{3}'   order by s.classname;
 select * from classes s where s.classname REGEXP  '[0-9]{3}'   order by s.classname;
image.png

^匹配字符串的開(kāi)始位置

 select * from classes s where s.classname REGEXP  '^p'   order by s.classname;
image.png

$ 匹配字符串的結(jié)束位置

 select * from classes s where s.classname REGEXP  '#$'   order by s.classname;
image.png

$ 匹配字符串最后三個(gè)字符是數(shù)字

 select * from classes s where s.classname REGEXP  '[0-9]{3,}$'   order by s.classname;
image.png

^ 與 $ 的結(jié)合使用
查詢以p開(kāi)頭1結(jié)尾中間有兩個(gè)任意字符的記錄

select * from classes s where s.classname REGEXP  '^p..1$' order by s.classname;
image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容