我正在使用这个ocde的开源
private String undoEscape(String searchTerm) {
String specialChars = "+-&|!(){}[]^\"~:\\";
for (int i = 0; i < specialChars.length(); i++) {
String character = specialChars.substring(i, i + 1);
String escaped = "\\" + character;
searchTerm = searchTerm.replaceAll(Pattern.quote(escaped), character);
}
return searchTerm;
}
如果在= =
中字符= \escaped = \\ - 在inspect = \
中searchTerm \\ n = in inspect = \ n
我收到了错误 怎么了?
java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:658)
at java.util.regex.Matcher.appendReplacement(Matcher.java:762)
at java.util.regex.Matcher.replaceAll(Matcher.java:906)
at java.lang.String.replaceAll(String.java:2162)
at org
答案 0 :(得分:1)
切换到replace()
,这也取代所有次出现,但不需要正则表达式:
private String unescape(String searchTerm) {
String specialChars = "+-&|!(){}[]^\"~:\\";
for (char c : specialChars.toCharArray()) {
String character = String.valueOf(c);
String escaped = "\\" + character;
searchTerm = searchTerm.replace(escaped, character);
}
return searchTerm;
}