Reputation: 57
I have a string which is a path taken dynamically from my system.
I store it in a string.
C:\Users\SXR8036\Downloads\LANE-914.xls
I need to pass this path to a read Excel file function, but it needs the backslashes to be replaced with forward slash.
And I want something like C:/Users/SXR8036/Downloads/LANE-914.xls
,
i.e., all backslashes replaced with forward ones.
With the String replace method, I am only able to replace with a-z characters, but it shows an error when I replace special characters.
something.replaceAll("[^a-zA-Z0-9]", "/");
I have to pass the String name to read a file.
Upvotes: 1
Views: 8460
Reputation: 12751
It's better in this case to use non-regex replace()
instead of regex replaceAll()
. You don't need regular expressions for this replacement and it complicates things because it needs extra escapes. Backslash is a special character in Java and also in regular expressions, so in Java if you want a straight backslash you have to double it up \\
and if you want a straight backslash in a regular expression in Java you have to quadruple it \\\\
.
something = something.replace("\\", "/");
Behind the scenes, replace(String, String)
uses regular expression patterns (at least in Oracle JDK) so has some overhead. In your specific case, you can actually use single character replacement, which may be more efficient (not that it probably matters!):
something = something.replace('\\', '/');
If you were to use regular expressions:
something = something.replaceAll("\\\\", "/");
Or:
something = something.replaceAll(Pattern.quote("\\"), "/");
Upvotes: 3
Reputation: 10964
To replace backslashes with replaceAll you'll have to escape them properly in the regular expression that you are using.
In your case the correct expression would be:
final String path = "C:\\Users\\SXR8036\\Downloads\\LANE-914.xls";
final String normalizedPath = path.replaceAll("\\\\", "/");
As the backslash itself is the escape character in Java Strings it needs to be escaped twice to work as desired.
In general you can pass very complex regular expressions to String.replaceAll
. See the JavaDocs of java.lang.String.replaceAll and especially java.util.regex.Pattern for more information.
Upvotes: 0