nantitv
nantitv

Reputation: 3733

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 : "Report\\n"

I tried the following way

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

But it's printing "Report\\\n"

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?

Upvotes: 4

Views: 319

Answers (5)

Tenzin
Tenzin

Reputation: 2505

For replacing multiple forward slashes with a single forward slash you could use:

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

For replacing multiple backward slashes with a single backward slash you could use:

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

Upvotes: -1

Maroun
Maroun

Reputation: 95958

If you print path, you'll get:

Report\\\n

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

You should do:

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

Explanation:

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.

Upvotes: 5

dtenreiro
dtenreiro

Reputation: 168

You just need the first and the last position of the "\" inside the String. Then create a String without the info between those positions.

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

Upvotes: 0

Murat Karagöz
Murat Karagöz

Reputation: 37594

You have to escape. A lot.

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

Prints out:

Report\\\n
Report\n

Upvotes: 1

Madgr
Madgr

Reputation: 7

You can use two method indexOf() and lastIndexOf() to get actual start and end index of string '\\....' Then simply get substring using substring method.

Upvotes: 0

Related Questions