Avoiding all special characters from a whole string at a time in Java

Lucene supports escaping special characters that are part of the query syntax. Special characters in the current list

+ - && || ! ( ) { } [ ] ^ " ~ * ? : \ 

To avoid these characters, use the \ character before the character. For example, to search for (1 + 1): 2, use the query:

 \(1\+1\)\:2 

My question is how to avoid a whole line at a time? For example myStringToEscape = "ABC^ " ~ * ? :DEF"; myStringToEscape = "ABC^ " ~ * ? :DEF"; How to get escapedString .

+6
source share
2 answers

You can use QueryParser.escape , for example:

 String escapedString = queryParser.escape(searchString); queryParser.parse("field:" + escapedString); 
+11
source

If you're just looking for a 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 
+3
source

All Articles