2012-01-16 191 views
4

我創建一個查詢的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); 
    }); 
}); 

但有時標題中有一個parenthese。這給我錯誤:

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

正在搜索的標題是貓(22)。

使正則表達式接受括號最簡單的方法是什麼?謝謝。

+0

你需要逃避你的模式括號:即'('應該是'\(',否則,正則表達式引擎認爲它是一個開放組字符有一個。例如,您需要特殊字符的數量才能轉義:例如,Google發現了[this](http://simonwillison.net/2006/Jan/20/escape/#p-6) – Xophmeister

+0

...另請參閱: http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex – Xophmeister

回答

10

你可以用code borrowed from this answer來逃避所有可能的正則表達式特殊字符。

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

我編輯了正則表達式,在正則表達式體中包含'|'字符,意味着聯合。沒有'|'可能有微妙的錯誤 –

+0

將're.excape(...)'在這裏工作? –

+0

感謝編輯@MikeSamuel。 – 2012-01-16 16:52:45