How to escape all Special Characters from whole st

2019-04-07 19:01发布

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.

标签: java lucene
2条回答
我命由我不由天
2楼-- · 2019-04-07 19:18

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
查看更多
3楼-- · 2019-04-07 19:25

You can use QueryParser.escape, such as:

String escapedString = queryParser.escape(searchString);
queryParser.parse("field:" + escapedString);
查看更多
登录 后发表回答