mysql中使用正則表達式查詢

基本形式

屬性名 regexp ‘匹配方式’

正則表達式的模式字符

^ 匹配字符開始的部分

eg1:  從info表name字段中查詢以L開頭的記錄

       select * from info where name regexp '^L';

eg2:  從info表name字段中查詢以aaa開頭的記錄

       select * from info where name regexp '^aaa';

$ 匹配字符結束的部分

eg1:   從info表name字段中查詢以c結尾的記錄

       select * from info where name regexp 'c$';

eg2:   從info表name字段中查詢以aaa結尾的記錄

       select * from info where name regexp 'aaa$';

.  匹配字符串中的任意一個字符,包括回車和換行

eg1:   從info表name字段中查詢以L開頭y結尾中間有兩個任意字符的記錄

      select * from info where name regexp '^L..y$';

[字符集合]匹配字符集合中的任意字符

eg1:   從info表name字段中查詢包含c、e、o三個字母中任意一個的記錄

      select * from info where name regexp '[ceo]';

eg2:   從info表name字段中查詢包含數字的記錄

       select * from info where name regexp '[0-9]';

eg3:   從info表name字段中查詢包含數字或a、b、c三個字母中任意一個的記錄

       select * from info where name regexp '[0-9a-c]';

[^字符集合]匹配除了字符集合外的任意字符

eg1:   從info表name字段中查詢包含a-w字母和數字以外字符的記錄

      select * from info where name regexp '[^a-w0-9]';

s1|s2|s3 匹配s1s2s3中的任意一個

eg1:   從info表name字段中查詢包含'ic'的記錄

      select * from info where name regexp 'ic';

eg2:   從info表name字段中查詢包含ic、uc、ab三個字符串中任意一個的記錄

      select * from info where name regexp 'ic|uc|ab';

*  代表多個該字符前的字符,包括0個或1個

eg1:   從info表name字段中查詢c之前出現過a的記錄

      select * from info where name regexp 'a*c';

+  代表多個該字符前的字符,包括1個

eg1:   從info表name字段中查詢c之前出現過a的記錄

      select * from info where name regexp 'a+c';(注意比較結果!)

字符串{N} 字符串出現N次

eg1:   從info表name字段中查詢出現過a3次的記錄

      select * from info where name regexp 'a{3}';

字符串{M,N}字符串最少出現M次,最多出現N次

eg1:   從info表name字段中查詢ab出現最少1次最多3次的記錄

      select * from info where name regexp 'ab{1,3}';

     

MySQL中自帶通配符(LIKE關鍵詞)

%可以表示任意長度的字符(包括0)

-可以表示單個字符

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章