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.
You can use QueryParser.escape
, such as:
String escapedString = queryParser.escape(searchString);
queryParser.parse("field:" + escapedString);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With