这是测试用例:
db.test.insert({ name: "john"});
db.test.insert({ name: "donny"});
db.test.insert({ name: "lenny"});
db.test.find({ name: { $regex: /^((?!nn)[\s\S])*$/}}); //works fine, returns only john
db.test.find({ name: { $regex: new RegExp("/^((?!nn)[\s\S])*$/")}}); //returns nothing
正则表达式应该返回不包含“nn”的对象,但在使用 RegExp 对象时它不起作用。我使用 Robomongo 对此进行了测试。
知道为什么吗?
最佳答案
使用 new RegExp
时,请勿包含前导和尾随 /
字符。这些仅与 JavaScript 中的文字表示法一起使用。您还需要转义字符串中的反斜杠。
db.test.find({ name: { $regex: new RegExp("^((?!nn)[\\s\\S])*$")}});
关于node.js - MongoDB 正则表达式不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26260904/