使用$regex进行文本匹配时遇到的诡异问题

oliseh 2017-12-13 01:23:54
使用 $regex时, 我们可以使用如下三种语法:

{ <field>: { $regex: /pattern/, $options: '<options>' } }
{ <field>: { $regex: 'pattern', $options: '<options>' } }
{ <field>: { $regex: /pattern/<options> } }

我们针对前两种语法进行了对比测试后得到了完全不同的效果
[size=13px][/size]

#测试用的集合
pradb>db.newtab.find()
{ "_id" : ObjectId("5a2a2555c8ba4994e594397f"), "f1" : "realapp" }
{ "_id" : ObjectId("5a2a255dc8ba4994e5943980"), "f1" : "racapp" }
{ "_id" : ObjectId("5a2a2562c8ba4994e5943981"), "f1" : "mysql" }
{ "_id" : ObjectId("5a2a2d60c8ba4994e5943982"), "f1" : "vcapp" }
{ "_id" : ObjectId("5a2a340fc8ba4994e5943983"), "f1" : "rea\napp" }
{ "_id" : ObjectId("5a2e4156c3b9a66ec4988f15"), "f1" : "suretrea" }

#使用单引号将字符串括起来,我们得到的查询结果是"realapp"
pradb>db.newtab.find({f1:{$regex:'rea \n# comment 1\nl',$options:"x"}})
{ "_id" : ObjectId("5a2a2555c8ba4994e594397f"), "f1" : "realapp" }

#使用/将字符串括起来,我们得到的查询结果是"rea\napp"
pradb>db.newtab.find({f1:{$regex:/rea \n# comment 1\nl/,$options:"x"}})
{ "_id" : ObjectId("5a2a340fc8ba4994e5943983"), "f1" : "rea\napp" }

// and ''为何会导致不同的结果输出?

...全文
289 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

1,798

社区成员

发帖
与我相关
我的任务
社区描述
MongoDB相关内容讨论区
社区管理员
  • MongoDB社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧