【问题标题】:MongoDB RegExp inconsistencyMongoDB 正则表达式不一致
【发布时间】:2014-12-03 08:23:38
【问题描述】:

这是测试用例:

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 对此进行了测试。

知道为什么吗?

【问题讨论】:

    标签: node.js mongodb mongoose robo3t


    【解决方案1】:

    在使用 new RegExp 时,不要包含前导和尾随 / 字符。这些仅与 JavaScript 中的文字表示法一起使用。您还需要转义字符串中的反斜杠。

    db.test.find({ name: { $regex: new RegExp("^((?!nn)[\\s\\S])*$")}});
    

    【讨论】:

      猜你喜欢
      • 2014-03-02
      • 2012-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多