mysql正则表达式关键字_《MySQL必知必会》正则表达式
《MySQL必知必會》正則表達(dá)式
正則表達(dá)式
1.1、關(guān)鍵字 REGEXP
正則表達(dá)式的使用需要用到關(guān)鍵字 REGEXP 。
select prod_name
from products
where prod_name regexp '1000';
從效果看和關(guān)鍵字 LIKE 有相似之處。但只從這個例子中看不出差別,而且使用正則表達(dá)式還會降低性能。
但是如果用 LIKE 替換上面的句子,是查詢不到數(shù)據(jù)的。
因?yàn)?LIKE 是匹配整個列內(nèi)的全文本才會返回數(shù)據(jù),要想做到和 REGEXP 一樣的效果,要使用通配符或者拼接函數(shù)才行。
正則表達(dá)式是需要配合起來使用才能看到它的擴(kuò)展性。
select prod_name
from products
where prod_name regexp '.000';
. 在正則表達(dá)式中表示任意一個字符。
以上例子使用的是數(shù)字匹配,要知道 MySQL 3.23.4+ 正則表達(dá)式匹配都是不區(qū)分大小寫的。
1.2、OR 匹配 ‘ | ’
select prod_name
from products
where prod_name regexp 'ton|1000|2000';
使用 | 可以起到 or 的作用,要注意,不要有多余的空格,將會影響匹配。可以給出兩個或兩個以上的條件。
1.3、匹配幾個字符之一
select prod_name
from products
where prod_name regexp '[125] ton';
用 [ ] 定義一組字符,以上的例子表示匹配 1 2 5 三個字符。注意 ton 前是有一個空格的。匹配的是 ‘1 ton' , '2 ton' ,'5 ton' 這三個字符串。
還有一種寫法,是使用 |
select prod_name
from products
where prod_name regexp '[1|2|5] ton';
得到的結(jié)果是和上面的一樣的。
但是要注意,下面這樣寫是得不到預(yù)期結(jié)果的。
select prod_name
from products
where prod_name regexp '1|2|5 ton';
因?yàn)樯厦鎸懛ǜ嬖V MySQL ,將匹配 1 , 2 ,5 ton 單個字符串
此外,還可以使用 ^ 來匹配這些字符以外的列。
select prod_name
from products
where prod_name regexp '[^123]';
^ 當(dāng)然也是不能匹配 NULL 值的列的。
1.4、匹配范圍
select prod_name
from products
where prod_name regexp '[1-5] ton';
' - ' 表示范圍,1-5,表示1、2、3、4、5 。
a-z 表示任意字母范圍。
1.5、特殊字符
上面提到 . 表示任意一個字符,那么如果需要匹配 '.' 要怎么才能讓MySQL知道不去轉(zhuǎn)義它?
答案是 反斜桿 \ 。
select prod_name
from products
where prod_name regexp '\\.';
還可以引用元字符:
元字符
說明
\\f
換頁
\\n
換行
\\r
回車
\\t
制表
\\v
縱向制表
匹配 \ 需要 \\\ 來表示。
1.6、匹配字符類
1.7、匹配多個實(shí)例
select prod_name
from products
where prod_name regexp '\\([1-5] sticks?\\)';
\\( :匹配 (;\\) :匹配 )
[1-5] : 匹配數(shù)字 1 -5 的范圍;
sticks? :需要拆分為 stick 和 s? 來看待,stick :匹配全文
s? : 表示 ? 前面的 s 為匹配0或1個,即為可選。
重復(fù)元字符說明如下表:
結(jié)合上表匹配字符類的元字符,還可以
select prod_name
from products
where prod_name regexp '[[:digit:]]{4}';
[:digit:] :表示匹配任意數(shù)字 ,{4} : 表示出現(xiàn)四次。
當(dāng)然還可以有其他寫法,如下:
select prod_name
from products
where prod_name regexp '[0-9][0-9][0-9][0-9]';
1.8、定位符
定位元字符說明如下:
想找以任意數(shù)字作為開頭的產(chǎn)品名:
select prod_name
from products
where prod_name regexp '^[1-9]';
想找以任意數(shù)字作為結(jié)尾的產(chǎn)品名:
select prod_name
from products
where prod_name regexp '[0-9]$';
注意 ^ 的兩種用法
用在[ ] 內(nèi)表示否定該集合,用在 [ ] 外表示文本的開始處。
總結(jié)
以上是生活随笔為你收集整理的mysql正则表达式关键字_《MySQL必知必会》正则表达式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql数据库表格怎么建立_mysql
- 下一篇: mysql树形遍历_mysql树形结构遍