admin管理员组

文章数量:1254251

I'm using elasticsearch in a NodeJS project, which is breaking upon entering one of the Lucene keywords into the search box. I'm looking for a simple implementation to escape their special characters. Is regex the best way? I've been fiddling with the regex for a bit now, and felt as if there were probably others that have already gone through this process.

I'm using elasticsearch in a NodeJS project, which is breaking upon entering one of the Lucene keywords into the search box. I'm looking for a simple implementation to escape their special characters. Is regex the best way? I've been fiddling with the regex for a bit now, and felt as if there were probably others that have already gone through this process.

Share Improve this question asked Oct 17, 2014 at 19:19 user2402831user2402831 67311 silver badges24 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 13

Just needed to fiddle more.

var escaped = query.replace(/([\!\*\+\&\|\(\)\[\]\{\}\^\~\?\:\"])/g, "\\$1");    

Globally replace all instances of the chars lucene would yell about with their escaped version.

I updated this to include all elasticsearch & Lucene reserved characters:

var pattern = /([\!\*\+\-\=\<\>\&\|\(\)\[\]\{\}\^\~\?\:\\/"])/g;

var str = "}the+S+entence you want]]to e*scape"

str = str.replace(pattern, "\\$1");

本文标签: Escaping Lucene Characters using Javascript RegexStack Overflow