简体   繁体   English

使用特殊字符创建正则表达式

[英]Creating regexp with special characters

I'm creating a query for mongodb: 我正在为mongodb创建一个查询:

app.get('content/:title',
function(req, res) {
  var regexp = new RegExp(req.params.title, 'i');

  db.find({
    "title": regexp,
  }).toArray(function(err, array) {
    res.send(array);
  });
});

But sometimes the title has a parenthese in it. 但有时标题中有一个括号。 This gives me the error: 这给了我错误:

SyntaxError: Invalid regular expression: /cat(22/: Unterminated group
    at new RegExp (unknown source)

The title that is being searched for is cat(22). 正在搜索的标题是cat(22)。

What's the easiest way to make the regex accept parenthesis? 使正则表达式接受括号的最简单方法是什么? Thanks. 谢谢。

您可以使用从此答案中借用的代码来转义所有可能的正则表达式特殊字符。

new RegExp(req.params.title.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"), "i");

Escape it with a backslash. 用反斜杠逃脱它。 And test it on a site like http://rejex.heroku.com/ 并在http://rejex.heroku.com/等网站上进行测试

/cat\(22/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM