Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape all Special Characters from whole string at one go in Java

Tags:

java

lucene

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.

like image 678
gozizibj Avatar asked Feb 26 '14 03:02

gozizibj


2 Answers

You can use QueryParser.escape, such as:

String escapedString = queryParser.escape(searchString);
queryParser.parse("field:" + escapedString);
like image 129
femtoRgon Avatar answered Nov 12 '22 21:11

femtoRgon


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
like image 25
ADDruid Avatar answered Nov 12 '22 19:11

ADDruid