nantitv nantitv - 1 year ago 61
Java Question

How to replace 'n' back slashes (\) with one?

I would like to squeeze out 'n' number of slashes into 1, where n is not fixed.

For example:

String path = "Report\\\\\\n";

Expected output :

I tried the following way

System.out.println(path.replaceAll("\\+", "\");

But it's printing

I am not able to reduce more than that.

All the related so question/answer related to fixed number of slashes.

Is there any generic way I can squeeze all backslashes to one?

Answer Source

If you print path, you'll get:


That's because \ should be quoted and it's written as \\ in Java.

You should do:

System.out.println(path.replaceAll("\\\\+", "\\\\"));


In (pure) regex, in order to match the literal \, you should quote it. So it's represented as:


In Java, \ is represented as \\, simple math should explain the 4 \s.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download