How to replace "n" backslashes (\) with one?

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

For instance:

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

Expected Result: "Report\\n"

I tried the following way

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

But he is typing "Report\\\n"

I can not reduce more.

All related questions / answers related to a fixed number of slashes.

Is there any general way I can compress all backslashes to one?

+4
source share
5 answers

If you print path, you will receive:

Report\\\n

This is because it \must be quoted and written as \\in Java.

You should:

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

Explanation:

() , \, . , :

\\

Java \ \\, 4 \ s.

+5

. .

System.out.println("Report\\\\\\n");
System.out.println("Report\\\\\\n".replaceAll("[\\\\]+", "\\\\"));

:

Report\\\n
Report\n
+1

indexOf() lastIndexOf(), '\\....' , .

0

"\" String. .

int firstIndex = path.indexOf("\\");
int lastIndex = path.lastIndexOf("\\");
String result = path.substring(0, firstIndex) + path.substring(lastIndex, path.length());
0

:

.replaceAll("(?)[//]+", "/"); 

:

.replaceAll("(?)[\\\\]+", "\\\\");
-1
source

Source: https://habr.com/ru/post/1649298/


All Articles