Reputation: 10841
why does this code throw an exception?
file = file.replaceAll(Pattern.quote("/"),File.separator);
Message: String index out of range: 1 File: null Class: java.lang.String Methode: charAt Line: -1 File: null Class: java.util.regex.Matcher Methode: appendReplacement Line: -1 File: null Class: java.util.regex.Matcher Methode: replaceAll Line: -1 File: null Class: java.lang.String Methode: replaceAll Line: -1
Upvotes: 1
Views: 1263
Reputation: 1502496
The second parameter of replaceAll
is also a pattern to some extent. In particular, backslash has a special meaning. However, you don't just want to use Pattern.quote
as that will quote more than you need to. You want to use Matcher.quoteReplacement
:
file = file.replaceAll(Pattern.quote("/"),
Matcher.quoteReplacement(File.separator));
Alternatively - and rather more simply - don't use regular expressions at all:
file = file.replace("/", File.separator);
Upvotes: 8