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

前端 未结 4 1662
清酒与你
清酒与你 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:31

    Use regular expression to replace those characters in one go.

    example:

     String s="some text && || []!{} ()^*?~ and ";
            Pattern p= Pattern.compile("([-&\\|!\\(\\){}\\[\\]\\^\"\\~\\*\\?:\\\\])");
    
            s=p.matcher(s).replaceAll("\\\\$1");
            System.out.println(s);\\prints some text \&\& \|\| \[\]\!\{\} \(\)\^\*\?\~ and 
    

提交回复
热议问题