当我尝试将`\\`替换为`\`时,为什么会出现StringIndexOutOfBoundsException?

Rak*_*yal 11 java string

我必须\\\Java 替换.我正在使用的代码是

System.out.println( (MyConstants.LOCATION_PATH + File.separator + myObject.getStLocation() ).replaceAll("\\\\", "\\") );
Run Code Online (Sandbox Code Playgroud)

但我不知道它为什么会扔StringIndexOutOfBoundsException.

它说 String index out of range: 1

可能是什么原因?我想这是因为第一个参数replaceAll接受了一个模式.可能的解决方案是什么?


堆栈跟踪

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
    at java.lang.String.charAt(String.java:558)
    at java.util.regex.Matcher.appendReplacement(Matcher.java:696)
    at java.util.regex.Matcher.replaceAll(Matcher.java:806)
    at java.lang.String.replaceAll(String.java:2000)
Run Code Online (Sandbox Code Playgroud)

找到答案

asalamon74发布了我需要的代码,但我不知道为什么他删除了它.无论如何这是它.

Java的bug数据库中已经存在一个bug.(感谢您的参考,asalamon.)

yourString.replaceAll("\\\\", "\\\\");
Run Code Online (Sandbox Code Playgroud)

令人惊讶的是,搜索和替换字符串都是相同的:)但它仍然做我需要的.

Jon*_*eet 17

使用String.replace而不是replaceAll使用正则表达式来避免它:

String original = MyConstants.LOCATION_PATH + File.seperator 
    + myObject.getStLocation();
System.out.println(original.replace("\\\\", "\\"));
Run Code Online (Sandbox Code Playgroud)

我个人不会这样做 - 我创建MyConstants.LOCATION_PATH_FILE作为a File然后你可以写:

File location = new File(MyConstants.LOCATION_PATH_FILE,
                         myObject.getStLocation());
Run Code Online (Sandbox Code Playgroud)

这将自动做正确的事情.

  • 你越接近现实,就越有可能获得有用的答案.但是,只使用"替换"仍然可以正常工作. (4认同)

use*_*421 8

好吧,我试过了

    String test = "just a \\ test with some \\\\ and others \\\\ or \\ so";
    String result = test.replaceAll("\\\\", "\\\\");
    System.out.println(test);
    System.out.println(result);
    System.out.println(test.equals(result));
Run Code Online (Sandbox Code Playgroud)

并且像预期的那样得到了

just a \ test with some \\ and others \\ or \ so
just a \ test with some \\ and others \\ or \ so
true
Run Code Online (Sandbox Code Playgroud)

你真正需要的

string.replaceAll("\\\\\\\\", "\\\\");
Run Code Online (Sandbox Code Playgroud)

要得到

just a \ test with some \\ and others \\ or \ so
just a \ test with some \ and others \ or \ so
false
Run Code Online (Sandbox Code Playgroud)

你想找到:\\  (2斜杠)
需要在正则表达式中转义:( \\\\ 4斜杠)
并在Java中转义:( "\\\\\\\\" 8斜杠)
相同的替换...


ste*_*ell 1

File.seperator 已经像任何字符串对象一样被转义,因此您将它们转义两次。

您只需转义作为字符串文字输入的值。