如何逃避reqexp以在MongoDB中查找文档?

时间:2022-08-15 19:18:47

I've simple regexp based searching via MongoDB like:

我通过MongoDB进行基于正则表达式的简单搜索:

router.get('/search', function (req, res, next) {
   var text = req.query.text;

   collection.find({text: new ReqExp(text, 'ig')}, function (err, result) {
      if (err) return next(err);

      return res.status(200).json({result: result});
   }); 
});

If user tries to search text like javascript MongoDB successfully find all documents by regular exception. But if he tried to search (javascript then MongoDB throws with the following exception:

如果用户试图像javascript一样搜索文本,MongoDB会成功找到所有文件,并且会定期查找异常。但如果他试图搜索(javascript然后MongoDB抛出以下异常:

[SyntaxError: Invalid regular expression: /(javascript/: Unterminated group]

[SyntaxError:无效的正则表达式:/(javascript /:Unterminated group]

What is the proper way to escape input text to prevent errors as above?

什么是逃避输入文本以防止上述错误的正确方法?

1 个解决方案

#1


0  

The problem with "(javascript" is that contains the special character "(" and it can be used as part of a pattern match expression. There are many other characters that can be part as regular expression as well: [,\,?,+. Each of them needs to be escaped with "\" to avoid interpretation of its special meaning. For example if the user enters "(javascript" the string "(javascript" would have been searched.

“(javascript”的问题是包含特殊字符“(”并且它可以用作模式匹配表达式的一部分。还有许多其他字符也可以作为正则表达式的一部分:[,\,?, +。每个都需要用“\”进行转义,以避免解释其特殊含义。例如,如果用户输入“(javascript”字符串“(javascript”将被搜索到。

The following URL is a very good source for understanding the patterns that can be used as part of RegExp:

以下URL是理解可以作为RegExp的一部分使用的模式的非常好的来源:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp

#1


0  

The problem with "(javascript" is that contains the special character "(" and it can be used as part of a pattern match expression. There are many other characters that can be part as regular expression as well: [,\,?,+. Each of them needs to be escaped with "\" to avoid interpretation of its special meaning. For example if the user enters "(javascript" the string "(javascript" would have been searched.

“(javascript”的问题是包含特殊字符“(”并且它可以用作模式匹配表达式的一部分。还有许多其他字符也可以作为正则表达式的一部分:[,\,?, +。每个都需要用“\”进行转义,以避免解释其特殊含义。例如,如果用户输入“(javascript”字符串“(javascript”将被搜索到。

The following URL is a very good source for understanding the patterns that can be used as part of RegExp:

以下URL是理解可以作为RegExp的一部分使用的模式的非常好的来源:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp