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

梦想的初衷 提交于 2019-12-19 05:35:07

问题


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

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

i am having problem escaping these characters because they are too many and if i use the String.replaceAll() method, i'll just end up having a really long line of code just for escaping the characters. what is the best way to do? thanks!


回答1:


There is also a method called QueryParser#escape, which may be useful:

Returns a String where those characters that QueryParser expects to be escaped are escaped by a preceding \.




回答2:


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 



回答3:


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)




回答4:


There is a Apache Commons Library for that: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html



来源:https://stackoverflow.com/questions/9323848/how-can-i-escape-a-group-of-special-characters-in-java-in-one-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!