SELECT prod_name FROM products WHERE prod_name REGEXP '1000' #检索列prod_name包含文本1000的所有行. ORDER BY prod_name; SELECT prod_name FROM products WHERE prod_name REGEXP '.000' #Like匹配整个列,而Regexp在列值内进行匹配. ORDER BY prod_name; SELECT prod_name FROM products WHERE prod_name REGEXP BINARY 'JetPack .000'; #默认MySQL正则匹配不区分大小写,如果想区分,可利用关键字Binary SELECT prod_name FROM products WHERE prod_name REGEXP '1000|2000' ORDER BY prod_name; SELECT prod_name FROM products WHERE prod_name REGEXP '[123] Ton' #匹配1或2或3, 而[^123]则匹配除这些字符外的任何东西 ORDER BY prod_name; SELECT prod_name FROM products WHERE prod_name REGEXP '[1-5] Ton' #匹配1到5,类似还有[0-9], [a-z] ORDER BY prod_name; SELECT vend_name FROM vendors WHERE vend_name REGEXP '\\.' #匹配如.、[]、|、-等特殊字符时,前面必须加\\, 为了匹配\,则要用\\\ ORDER BY vend_name; SELECT prod_name FROM products WHERE prod_name REGEXP '\\([0-9] sticks?\\)' #sticks?表示匹配stick或sticks,即s使可选的。 ORDER BY prod_name; SELECT prod_name FROM products WHERE prod_name REGEXP '[[:digit:]]{4}' #匹配连在一起的4位数字 ORDER BY prod_name; SELECT prod_name FROM products WHERE prod_name REGEXP '^[0-9\\.]' #找出以一个数或一个小数点开始的所有产品 ORDER BY prod_name; SELECT '.AB' REGEXP '^[0-9\\.]'; #正则表达式测试,总是返回0(没有匹配)或返回1(匹配) #注意, 符号^有两种用法,在集合中(用[和]定义),用它否定该集合,否则用于指串的开始处。
附录:
\\也用来引用元字符(具有特殊含义的字符),如表9-1
下表列出了一些常用的匹配字符类:
正则表达式中常用重复元字符如下表:
正则表达式中常用定位元字符如下表: