Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java how to replace backslash? [duplicate]

Tags:

java

regex

In java, I have a file path, like 'C:\A\B\C', I want it changed to ''C:/A/B/C'. how to replace the backslashes?

like image 797
user534009 Avatar asked Apr 22 '11 15:04

user534009


People also ask

How do you replace a single backslash with double backslash in Java?

Replacing a Single Backslash( \ ) With a Double Backslash( \\ ) Using the replaceAll() Method. This is another solution that you can use to replace the backslashes. Here, we used the replaceAll() method that works fine and returns a new String object.

How do you replace a single backslash in a string in Java?

Answers. In Java strings, \ is the escape character. The string "\t" represents a TAB control character. If you want a Java \, you need to pass in two backslashes.

How do you get rid of a double slash in Java?

replaceAll("//", "/");

How do you replace a backslash?

To replace all backslashes in a string:Call the replaceAll() method, passing it a string containing two backslashes as the first parameter and the replacement string as the second. The replaceAll method will return a new string with all backslashes replaced by the provided replacement.


3 Answers

    String text = "C:\\A\\B\\C";
    String newString = text.replace("\\", "/");
    System.out.println(newString);
like image 159
Jim Blackler Avatar answered Oct 04 '22 20:10

Jim Blackler


Since you asked for a regular expression, you'll have to escape the '\' character several times:

String path = "c:\\A\\B\\C";
System.out.println(path.replaceAll("\\\\", "/"));
like image 26
Isaac Truett Avatar answered Oct 04 '22 20:10

Isaac Truett


You can do this using the String.replace method:

public static void main(String[] args) {
    String foo = "C:\\foo\\bar";
    String newfoo = foo.replace("\\", "/");
    System.out.println(newfoo);
}
like image 34
bedwyr Avatar answered Oct 04 '22 22:10

bedwyr