user1365697 February 2016

error in replaceAll with escp

I am using open source with this 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;
    }

in case that the character = \ in inspect = \

escaped = \\ - in inspect = \

searchTerm \\n = in inspect = \n

I got error what is wrong ?

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

Answers


Sasha Salauyou February 2016

Switch to replace(), which also replaces all occurrences but doesn't require regex:

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;
}

Post Status

Asked in February 2016
Viewed 2,645 times
Voted 8
Answered 1 times

Search




Leave an answer