如何使用“+”(加号)等特殊字符处理mongodb正则表达式?

时间:2016-01-13 04:55:55

标签: mongodb meteor

我想在文档中搜索具有特殊字符的值,例如“+”。

variable = 'test+test.test';

我想用.*variable.*

搜索值

例如,

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

以上查询无效

3 个答案:

答案 0 :(得分:0)

  

我想用.*variable.*

搜索值

您无需使用星号运算符.*variable.*进行搜索。

以下内容同样合适:

// returns all keys with "variable" somewhere in the string
db.myCollection.find({ myKey : /variable/i});
  

我想在文档中搜索具有特殊字符的值,例如“+”。

如果您想使用正则表达式执行此操作,只需使用+转义\字符:

db.myCollection.find({ myKey : /test\+test/i});

答案 1 :(得分:0)

variable = 'test\+test\.test';

然后

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

答案 2 :(得分:0)

我已经解决了问题,这是有效的代码。

string = "abcd+1234@gmail.com";

Meteor js query example: {'emails.address': {'$regex': '.*' + Helpers.escapeRegExp(string) + '.*', '$options': 'i'}},


escapeRegExp: function (string) {
    if (string) {
       return string.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
       
    }
}
It should be abcd\+1234@gmail\.com after call escapeRegExp function.

相关问题