$regex基本語法#
{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }
{ <field>: /pattern/<options> }//省略regex
pattern為正則表達式
options為配置選項
Option | 介紹 | 限制 | 示例 |
---|---|---|---|
i |
忽略大小寫情況 | 無 | 示例二 |
m |
多行匹配模式,當(dāng)有錨點^和$其屏,且文檔為多行時,分行進行開頭結(jié)尾匹配缨该,而不是對字符串開頭結(jié)尾進行匹配偎行。 | 無 | 示例三 |
x |
忽略非轉(zhuǎn)義的空白字符 |
$regex 和$options 不能省略 |
示例四 |
s |
點號(.)元字符會匹配所有字符,包括換行符(\n) |
$regex 和$options 不能省略 |
示例五 |
以上配置內(nèi)容可組合使用
示例:
-
一贰拿、無配置選項
1.查找article_abstract_en字段中蛤袒,含“l(fā)iterature”的數(shù)據(jù)
db.getCollection("regex").find({article_abstract_en: { $regex: /literature/}});
db.getCollection("regex").find({article_abstract_en: { $regex: 'literature'}});
db.getCollection("regex").find({article_abstract_en: /literature/});
結(jié)果相同且均為20條
2.查找article_authors字段中,含數(shù)字的數(shù)據(jù)
db.getCollection("regex").find({article_authors: { $regex: '\\d'} });
db.getCollection("regex").find({article_authors: { $regex: /\d/} });
db.getCollection("regex").find({article_authors: /\d/} );
三種語句結(jié)果相同膨更,均為51條
省略“/”的語句會將元字符中
\
忽略,需要用\\
才能正常使用元字符:
db.getCollection("regex").find({article_authors: { $regex: '\d'} });
結(jié)果為280條妙真,且含結(jié)果只匹配的字母“d”,含無數(shù)字數(shù)據(jù)
-
二荚守、配置“i”應(yīng)用:忽略大小寫
1.查找article_abstract_en中含“Some”的數(shù)據(jù)
未忽略大小寫時查詢結(jié)果
結(jié)果共7條
db.getCollection("regex").find({article_abstract_en:{$regex:/Some/,$options:'i'}});
db.getCollection("regex").find({article_abstract_en:{$regex:'Some',$options:'i'}});
db.getCollection("regex").find({article_abstract_en:{$regex:/Some/i}});
db.getCollection("regex").find({article_abstract_en:/Some/i });
四種語句結(jié)果相同珍德,均為64條
-
三、配置“m”應(yīng)用:多行匹配
1.查找article_abstract_en中矗漾,以This開頭的數(shù)據(jù)
無m時查詢結(jié)果:
結(jié)果共5條
db.getCollection("regex2").find({article_abstract_en:{$regex:/^This/,$options:'m'}});
db.getCollection("regex2").find({article_abstract_en:{$regex:'^This',$options:'m'}});
db.getCollection("regex2").find({article_abstract_en:{$regex:/^This/m}});
db.getCollection("regex2").find({article_abstract_en:/^This/m });
結(jié)果均為7條锈候,第四條與第七條第一行并不是以“This”開頭
- 四、配置“x”應(yīng)用
db.getCollection("regex2").find({article_title:{$regex:/O ct/,$options:'x'}});
db.getCollection("regex2").find({article_title:{$regex:'O #month\n ct#month\n',$options:'x'}});
/*其中 "#month\n"為字符串中的注釋敞贡,以“#”開始泵琳,“\n”結(jié)束,僅無“/”模式下可用*/
結(jié)果相同,均匹配到“October”
$regex
和$options
都不可省略誊役,否則會有以下報錯
[Error] SyntaxError: invalid regular expression flag x
- 五获列、配置“s”應(yīng)用
db.getCollection("regex2").find({article_title:{$regex:/Reg.*Mission/,$options:'s'}});
db.getCollection("regex2").find({article_title:{$regex:'Reg.*Mission',$options:'s'}});
字段中存在換行符,若無“s”蛔垢,則結(jié)果為空
$regex
和$options
都不可省略击孩,否則會有以下報錯
[Error] SyntaxError: invalid regular expression flag s