public static String getPortableFilePath(String target)
{
Pattern ptr=Pattern.compile("[\\|/]+");
Matcher mtr=ptr.matcher(target);
return mtr.replaceAll(File.separator);
}
public static void main(String[] args)
{
System.out.println(getPortableFilePath("C:///Program Files////Java\\jdk1.6.0_23/bin"));
}
In the above code I am trying to replace all the Forward and Backward slashes with the current systems File Separator. Code compiles fine when put into a class, but when executed it gives an array index out of bounds exception. Any guesses why?
The Exception:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(Unknown Source)
at java.util.regex.Matcher.appendReplacement(Unknown Source)
at java.util.regex.Matcher.replaceAll(Unknown Source)
at Files.getPortableFilePath
at Files.main
You need to get two backslashes through to the regex engine. Otherwise it will think you are escaping the next character. So use
for the pattern string. That way it resolves to the pattern
This is the problem with the string and the regex notation both using backslashes, and there being no way to skip the string interpolation stage.
And don’t use a vertical pipe in a square-bracket charclass: it is a literal there.