1. 程式人生 > >Mysql之正則匹配

Mysql之正則匹配

like strong 正則匹配 pda lec update highlight tor 精華

Regex與Like的關系
Mysql中我們經常會用到正則表達式就是Like filed like ‘%?%‘ 。但是有時對於一些復雜場景下的正則過濾,單單一個like就顯得有些力不從心了

Regex的精華就是 ‘‘ , like ‘%%‘ = regex ‘‘,特殊字符如^、$可以改變%的意思。

  • like ‘%304%‘ = regex ‘304‘
  • like ‘張%‘ = regex ‘^張‘
  • like ‘%03‘ = regex ‘03$‘
  • like ‘%3%‘ or like ‘%4%‘ = regex ‘[34]‘ 一個字段包含3或者包含4
  • like ‘%3%‘ or like ‘%4%‘ = regex ‘3|4‘ 一個字段包含3或者包含4
     
# 示例SQL---
# ‘‘ 匹配fw_ver字段中包含‘304‘字符串的所有數據:
select * from tbl_upgrade_policy where fw_ver like ‘%304%‘;
select * from tbl_upgrade_policy where fw_ver REGEXP ‘304‘;

# ^ 匹配輸入字符串的開始位置
# 查找operator字段已‘張‘開頭的記錄
select * from tbl_upgrade_policy where operator like ‘張%‘;
select * from tbl_upgrade_policy where operator regexp ‘^李‘;

# $ 匹配輸入字符串的結束位置
# 查找operator字段已‘03‘結尾的記錄
select * from tbl_upgrade_policy where operator like ‘%03‘;
select * from tbl_upgrade_policy where operator regexp ‘03$‘;

# [...] 字符集合,匹配所包含的任意一個字符。
# 查詢出update_type字段下為3或4或5中的任意數字
select * from tbl_upgrade_policy where update_type like ‘%3%‘ or update_type like ‘%4%‘ or update_type like ‘%5%‘;
select * from tbl_upgrade_policy where update_type REGEXP ‘[345]‘;

# p1|p2|p3 匹配 p1 或 p2 或 p3。
select * from tbl_upgrade_policy where update_type like ‘%3%‘ or update_type like ‘%4%‘;
select * from tbl_upgrade_policy where update_type REGEXP ‘3|4‘;

select * from tbl_upgrade_policy where update_type like ‘3%‘ or update_type like ‘%5‘;

# 註意:‘^[3,5]‘ 匹配以 3或,或5開頭的記錄
select * from tbl_upgrade_policy where update_type REGEXP ‘^[3,5]|4$‘;

# ‘^3,5‘ 匹配以 3,5 開頭的記錄
select * from tbl_upgrade_policy where update_type REGEXP ‘^3,5|2$‘;

  

Mysql之正則匹配