how can i escape a group of special characters in java in one method?

前端 未结 4 1661
清酒与你
清酒与你 2021-01-11 19:56

i use lucene search but lucene has a bunch of special characters to escape like:

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

i am havin

4条回答
  •  迷失自我
    2021-01-11 20:37

    Use regular expression. String.replaceAll() supports regular expression, so you can solve this problem using one single call. Just be careful: some of these characters are special for regular expressions too, so they mus be escaped "twice":

    str.replaceAll("([-\\&\\|!\\(\\)\\{\\}\\[\\]\\^\\"~\\*\\?:\\])", "\\$1");

    (I have not tried this, probably this line needs some fixes, but this is the idea)

提交回复
热议问题