Kevin Meredith
Kevin Meredith

Reputation: 41909

Java replaceAll with Backslashes

For this simple program ...

import java.lang.String;

public class test {

    public static void main(String[] argv) {

        String s = "Hello <BSLASH>";
        String sReplaced = s.replaceAll("<BSLASH>", "\\\\");

        System.out.println("s = " + s);
        System.out.println("sReplaced = " + sReplaced);

    }
}

Why doesn't sReplaced equal Hello \\ with 2 backslashes?

$javac test.java
$ java test
s = Hello <BSLASH>
sReplaced = Hello \

Upvotes: 2

Views: 489

Answers (4)

Ricky
Ricky

Reputation: 295

I also suggest to use replace instead replaceAll . I write here a code to fix the issue, and to try to explain how use Backslash in java string.

String bs1="\\";
String bs2="\\";
String sReplaced = s.replace("<BSLASH>", bs1.concat(bs2));

Upvotes: -1

PermGenError
PermGenError

Reputation: 46408

you should use total of 8 backslash's to get 2 backslashes. single backslash should be escaped with one backslash,backslash is a meta character is regex world, in-order to consider it as a normal character you will have to escape it againwith two backslash's.

 String sReplaced = s.replaceAll("<BSLASH>", "\\\\\\\\");

Upvotes: 1

arshajii
arshajii

Reputation: 129507

Don't use replaceAll for this, use replace:

String sReplaced = s.replace("<BSLASH>", "\\\\");

replaceAll takes a regular expression, which is not necessary here (this is why \\\\ evaluates to \).

Oh, and you really don't need import java.lang.String - the String class is imported by default.

Upvotes: 3

mezzie
mezzie

Reputation: 1296

Since replaceAll uses regex, it actually does escape four slashes to two then the escape for backslash is another backslash.

So your code is actually just \

To Replace it with two backslash, it should be

String sReplaced = s.replaceAll("<BSLASH>", "\\\\\\\\");

Upvotes: 2

Related Questions