简体   繁体   中英

replace special character String with another Special character

I have a String which is 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 read excel file function , but it needs the backward slashes to be replaced with forward slash.

and i want something like C:/Users/SXR8036/Downloads/LANE-914.xls ie all backward slash replaced with forward one

With String replace method i am only able to replace with a az character , but it shows error when i replace Special characters

something.replaceAll("[^a-zA-Z0-9]", "/");

I have to pass the String name to read a file.

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("\\"), "/");

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM