替换String中的所有反斜杠

时间:2012-10-26 11:00:49

标签: java regex

我正在尝试将所有\替换为%5C但输出错误:

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

3 个答案:

答案 0 :(得分:8)

变量str不包含反斜杠。您以某种方式正确地转义了replaceAll() args中的反斜杠,但未转移到str的原始作业中。

String str="a\b";

应该成为:

String str="a\\b";

答案 1 :(得分:3)

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

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

答案 2 :(得分: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.

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