文章目录
用正则表达式进行搜索基本字符匹配进行OR匹配匹配几个字符之一匹配范围匹配特殊字符匹配多个实例定位符全文本搜索使用全文本搜索启用全文本搜索支持进行全文本搜索用正则表达式进行搜索
正则表达式是用来匹配文本的特殊的串(字符集合)。
基本字符匹配
检索列prod_name包含文本1000的所有行:
regexp ‘1000’ 与文字正文1000匹配的一个正则表达式
select prod_name from productswhere prod_name regexp '1000' order by prod_name;
.是正则表达式语言中一个特殊的字符,它表示匹配任意一个字符。
select prod_name from productswhere prod_name regexp '.000' order by prod_name;
‘.000’ 能匹配1000和2000。
进行OR匹配
搜索两个串之一,使用|。
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' order by prod_name;
使用了正则表达式[123] ton。 [123]定义一组字符,它的意思是匹配1或2或3,因此, 1 ton和2 ton都匹配。[]是另一种形式的OR语句,[123] ton相当于[1|2|3] ton(不是1|2|3 ton,有[])。[^123] 却匹配除这些字符外的任何东西。
匹配范围
匹配数字0到9:[123456789]或[1-9]
[a-z]
表示任意字母
select prod_name from productswhere prod_name regexp '[1-5] ton' order by prod_name;
匹配特殊字符
为了匹配特殊字符,必须用\为前导。\-表示查找-, \.表示查找.。
select vend_name from vendors where vend_name regexp '\\.' order by vend_name;
匹配多个实例
select prod_name from products where prod_nameregexp '[[:digit:]]{4}' order by prod_name;#[[:digit:]]{4}匹配连在一起的任意4位数字
定位符
为了匹配特定位置的文本,需要使用以下定位符:
select prod_name from products where prod_name regexp '^[0-9\\.]' order by prod_name;#^[0-9\\.]串中第一个字符为.或任意数字
全文本搜索
使用全文本搜索
启用全文本搜索支持
CREATE TABLE productnotes(note_id int NOT NULL AUTO_INCREMENT,prod_id char(10)NOT NULL,note_date datetime NOT NULL,note_text textNULL ,PRIMARY KEY(note_id),FULLTEXT(note_text)) ENGINE=MyISAM;
FULLTEXT(note_text)定义了全文搜索。
进行全文本搜索
select note_text from productnotes where Match(note_text) Against('rabbit');
Match()指定被搜索的列, Against()指定要使用的搜索表达式。
匹配包含heavy但不包含任意以rope开始的词的行:
select note_text from productnoteswhere match(note_text) against('heavy -rope*' in boolean mode);
select note_text from productnoteswhere match(note_text) against('+rabbit +bait' in boolean mode);
搜索匹配包含词rabbit和bait的行
select note_text from productnotes where match(note_text) against('rabbit bait' in boolean mode);
搜索匹配包含rabbit和bait中的至少一个词的行
select note_text from productnotes where match(note_text) against('"rabbit bait"' in boolean mode);
搜索匹配短语rabbit bait而不是匹配两个词rabbit和bait
select note_text from productnoteswhere match(note_text) against('>rabbit <carrot"' in boolean mode);
匹配rabbit和carrot,增加前者的等级,降低后者的等级
select note_text from productnoteswhere match(note_text) against('+safe +(<combination)' in boolean mode);
索匹配词safe和combination,降低后者的等级