Reputation: 285
Lucene supports escaping special characters that are part of the query syntax. The current list special characters are
+ - && || ! ( ) { } [ ] ^ " ~ * ? : \
To escape these character use the \ before the character. For example to search for (1+1):2 use the query:
\(1\+1\)\:2
My question is how to escape from whole string at one go? For example myStringToEscape = "ABC^ " ~ * ? :DEF";
How to get a escapedString.
Upvotes: 7
Views: 15150
Reputation: 196
If you are just looking for simple replacement, this will do the trick.
String regex = "([+\\-!\\(\\){}\\[\\]^\"~*?:\\\\]|[&\\|]{2})";
String myStringToEscape = "ABC^ \" ~ * ? :DEF";
String myEscapedString = myStringToEscape.replaceAll(regex, "\\\\$1");
System.out.println(myEscapedString);
This will output:
ABC\^ \" \~ \* \? \:DEF
Upvotes: 4
Reputation: 33351
You can use QueryParser.escape
, such as:
String escapedString = queryParser.escape(searchString);
queryParser.parse("field:" + escapedString);
Upvotes: 14