replace() and replaceAll() in Java

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 04:46:10
Amit Deshpande

From Javadoc String.replaceAll

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.

System.out.println(a.replaceAll("/", Matcher.quoteReplacement("\\")));
Yogendra Singh

Why does this method when used with only two slashes like this a.replaceAll("/", "\") throw java.lang.StringIndexOutOfBoundsException?

As you know, \ is a metacharacter in regex. When you use \ in regex, it is always followed by another character e.g. \d or \s.

Your java.lang.StringIndexOutOfBoundsException exception is coming when it tries to evaluate the pattern string ITSELF i.e. \\ and it doesn't find a following character, which is mandatory in this case. This is not coming on the argument string a --> abc/xyz as It tries to do below:

if (nextChar == '\\') {  //<-- \\ is read here
    cursor++;

    //<--Its attempting to read next character and fails
    nextChar = replacement.charAt(cursor); 
    result.append(nextChar);
    cursor++;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!