用正则表达式进行搜索

以下的匹配都试图匹配单词出现。如果存在一个匹配则被检索出来。

  1. 检索列prod_name包含文本1000的所有行
    select prod_name from products where prod_name REGEXP '1000' order by prod_name;

  2. .在正则中表示一个字符
    select prod_name from products where prod_name REGEXP '.000' order by prod_name;
    结果: Jet 1000
    Jet 2000

  3. OR匹配
    select prod_name from products where prod_name REGEXP '1000|2000' order by prod_name;

  4. 如果想匹配特定字符怎么办
    select prod_name from products where prod_name REGEXP '[123] Ton' order by prod_name;

  5. 否定字符集
    select prod_name from products where prod_name REGEXP '[^123] Ton' order by prod_name;

  6. 匹配范围: 含有1-5 Ton就行,不管前面后面有没有东西
    select prod_name from products where prod_name REGEXP '[1-5] Ton' order by prod_name;
    结果:.5 Ton
    1 Ton
    2 Ton

  7. 转义字符,包括‘. \ | []’
    为了匹配特殊字符,必须使用\为前导。\-表示查找-, \.表示查找.
    select vend_name from vendors where vend_name REGEXP '\\.' order by vend_name;
    结果: Furball INC.

其他语言中用单个\来转义,但是mysql中\来转义

匹配字符类

说明
:alnum: 任意字母和数字(同[a-zA-z])
:alpha: 任意字符(同a-zA-Z)
:blank: 空格和制表(同\t)
:digit: 任意数字,同[0-9]
:lower: 任意小写字母,同[a-z]
:upper: 任意大写字母,同[A-Z]

如果匹配多个字符
重复元字符

元字符 说明
* 0个或者多个匹配
+ 1个或者多个匹配 等于'{1, }'
0个或者1个匹配 等于 '{0,1}'
n 指定数目的匹配
'{n,}' 不少于指定数目的匹配
'{n, m}' 匹配数目的范围 m不超过255

一些例子

  1. select prod_name from products where prod_name REGEXP '\\([0-9] sticks?\\)'
    结果: prod_name
    TNT (1 stick)
    TNT (1 sticks)
    s? s后的?使s可选,使前面任意一个字符出现0次或者1次

  2. 匹配连在一起的4位数字
    select prod_name from products where prod_name REGEXP '[[:digit:]{4}]'
    select prod_name from products where prod_name REGEXP '[0-9][0-9][0-9][0-9]'

[:digit:] 匹配任意数字,{4}确切要求它前面任意字符(任意数字)出现4次

  1. 以数字或者.开头,$文件结尾
    select prod_name from products where prod_name REGEXP '^[0-9\\.]' order by prod_name
posted @ 2024-05-28 15:12  肥梁  阅读(53)  评论(0)    收藏  举报