“\\\\".replaceAll(“\\\\", “\\") 抛出 java.lang.StringIndexOutOfBoundsException [英] "\\\\".replaceAll("\\\\", "\\") throws java.lang.StringIndexOutOfBoundsException

查看:58
本文介绍了“\\\\".replaceAll(“\\\\", “\\") 抛出 java.lang.StringIndexOutOfBoundsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java 中的以下代码片段:

The following code fragment in Java:

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

抛出异常:

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

javadoc on replaceAll 确实包含关于使用反斜杠的警告,并建议使用 Matcher.replaceAllMatcher.quoteReplacement.有人有关于如何用单个反斜杠替换字符串中所有出现的两个反斜杠的片段吗?

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 ?

上面显示的实际文字只是一个例子,实际的字符串可以在不同的地方多次出现两个连续的反斜杠.

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

推荐答案

你可以用 String#replace():-

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

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

<小时>

String#replaceAll 接受一个 regex 作为参数.因此,您必须将 反斜杠 转义两次.一次用于 Java,然后用于 Regex.因此,使用 replaceAll 的实际替换看起来像:-


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("\\\\\\\\", "\\\\")

但您在这里并不真正需要 replaceAll.

But you don't really need a replaceAll here.

这篇关于“\\\\".replaceAll(“\\\\", “\\") 抛出 java.lang.StringIndexOutOfBoundsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆