“\\\\”.replaceAll(“\\\\”, “\\”) throws java.lang.StringIndexOutOfBoundsException

与世无争的帅哥 提交于 2019-12-07 01:34:27

问题


The following code fragment in Java:

"\\\\".replaceAll("\\\\", "\\");

throws the exception:

java.lang.StringIndexOutOfBoundsException: String index out of range: 1 (NO_SOURCE_FILE:0)

The javadoc on replaceAll does include a caveat on the use of backslashes and recommends using Matcher.replaceAll or Matcher.quoteReplacement. Does anybody have a snippet on how to replace all occurrences of two backslashes in a string with a single backslash ?

clarification

The actual literal shown above is only an example, the actually string can have many occurrences of two consecutive backslashes in different places.


回答1:


You can simply do it with String#replace(): -

"\\\\".replace("\\\\", "\\")

String#replaceAll takes a regex as parameter. So, you would have to escape the backslash twice. Once for Java and then for Regex. So, the actual replacement using replaceAll would look like: -

"\\\\".replaceAll("\\\\\\\\", "\\\\")

But you don't really need a replaceAll here.




回答2:


Try this instead:

"\\\\".replaceAll("\\{2}", "\\")

The first parameter to replaceAll() is a regular expression, and {2} indicates that exactly two occurrences of the char must be matched.




回答3:


If you want to use Matcher.replaeAll() then you want something like this:

Pattern.compile("\\\\\\\\").matcher(input).replaceAll("\\\\");



回答4:


If you have backslash in replacement string, it will be treated as escape character and the method will try to read the next character.That is why , it is throwing StringIndexOutOfBoundsException.



来源:https://stackoverflow.com/questions/14650064/replaceall-throws-java-lang-stringindexoutofboundsexception

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