【问题标题】:Regex in MongoDB is not matching special characters [duplicate]MongoDB中的正则表达式不匹配特殊字符[重复]
【发布时间】:2020-07-24 12:57:53
【问题描述】:

我想在文档中搜索具有特殊字符的值,例如 ? ! $ / . @ > #

我想搜索?test等值,

例如,

db.myCollection.find({ myKey : /.*?test.*/i }); 

db.myCollection.find({ myKey : { '$regex' : '.*?test.*','$options' : 'i' });

我应该在这里改变什么?

【问题讨论】:

    标签: node.js regex mongodb special-characters string-matching


    【解决方案1】:

    您需要对特殊字符进行双重转义:

    db.collection.find({
      myKey: {
        $regex: "\\?test",
        "$options": "i"
      }
    })
    

    https://mongoplayground.net/p/oaRlSJvFNG_

    【讨论】:

    • 为什么投反对票?这有什么问题?
    • 嘿丹尼尔。它适用于除“#”之外的所有内容。有什么解决办法吗? (不确定是否反对。但那不是我)
    猜你喜欢
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多