4

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?

Maroun
  • 94,125
  • 30
  • 188
  • 241
nantitv
  • 3,539
  • 4
  • 38
  • 61
  • 1
    Check out [this posting](https://stackoverflow.com/questions/4025482/cant-escape-the-backslash-with-regex) for a good explanation of backslash escaping. – Markus L Jul 27 '16 at 14:48
  • According to [documentation](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String) ) you should avoid replacing with single `backslash` using `String.replaceAll()`. It's recomended to use `Matcher`. – xenteros Jul 27 '16 at 14:49

5 Answers5

5

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.

Maroun
  • 94,125
  • 30
  • 188
  • 241
1

You have to escape. A lot.

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

Prints out:

Report\\\n
Report\n
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
0

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

Madgr
  • 7
  • 4
0

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());
Klitos Kyriacou
  • 10,634
  • 2
  • 38
  • 70
dtenreiro
  • 168
  • 5
-1

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("(?)[\\\\]+", "\\\\");
Tenzin
  • 2,415
  • 2
  • 23
  • 36
  • Why is my post -1, I tried my code out and it works. (Also i was one of the first to post... :-S) Can the one who downvoted my post at least give an explenation why it would be a negative answer. – Tenzin Jul 27 '16 at 17:57