minil
minil

Reputation: 7135

Java replaceAll to replace special characters

I am looking for a snippet in java that replaces the

 "..", "/" or "\" or ":" - FileSeperator characters with
 "" 

in a fileName property passed from UI. This should be OS independent. Also I dont want to remove the "single dot", only "two dots"

Currently i wrote a snippet

private static void filter(){
    // should not remove the Single Dot
    String fileName = "/user/../142552/ReportFile.txt"      
    fileName = fileName.replaceAll("[/|\\|..|:|]","");
    System.out.println("fileName " + fileName); 
}

Output

fileName user142552ReportFiletxt

Expected Output

fileName user142552ReportFile.txt

Upvotes: 2

Views: 345

Answers (2)

Ian Roberts
Ian Roberts

Reputation: 122364

fileName.replaceAll("[/|\\|..|:|]","")

That regular expression is suspect - it will remove all occurrences of the characters /, |, . and :, which I doubt is what you had in mind. Try something more like this instead:

fileName.replaceAll("/|\\\\|:|\\.\\.","")

Backslashes are a nightmare in Java regular expressions because you have to double them anyway in string literals, and then double them again in regular expressions (so you need \\\\ to match a single backslash). Also the dot on its own is special in regex (matching any single character) so to match a literal dot you need the regex \., which means the Java string literal \\.

Upvotes: 4

nightograph
nightograph

Reputation: 2249

assuming that you have problem removing double \ (because by looking at your expression that wouldn't work) you should change it to:

fileName = fileName.replaceAll("[/\\\\.:]","");

Upvotes: 0

Related Questions