0

我正在尝试\%5C错误的输出替换所有内容:

String str="a\b";
str=str.replaceAll("\\\\", "%5C");
System.out.println(str);
4

3 回答 3

8

该变量str不包含反斜杠。您以某种方式正确地转义了replaceAll()args 中的反斜杠,但在原始分配中却没有str

String str="a\b";

应该变成:

String str="a\\b";
于 2012-10-26T11:02:54.273 回答
3

replaceAll返回结果,因此您应该尝试将结果分配给您的变量:

        // TODO Auto-generated method stub
        String str="a\b";
        str = str.replaceAll("\\\\", "%5C");
        System.out.println(str);
于 2012-10-26T11:03:29.077 回答
1

我认为首先你必须改变你的str因为它不正确根据你。
使用以下代码:

    // TODO Auto-generated method stub
    String str="a\\b";
    str=str.replaceAll("\\\\", "%5C");
    System.out.println(str);

您的代码不起作用,因为

A character preceded by a backslash (\) is an escape sequence and has special 
meaning to the compiler. The following table shows the Java escape sequences.

这意味着在 a\b\b中具有特殊含义Insert a backspace in the text at this point. Escape Sequences
这就是为什么它不起作用,所以你必须逃脱\角色。

于 2012-10-26T11:08:07.593 回答