Java Reference
In-Depth Information
at java.util.regex.Matcher.replaceAll(Matcher.java:806)
at java.lang.String.replaceAll(String.java:2000)
at com.javapuzzlers.MeToo.main(MeToo.java:6)
Although this behavior is platform dependent, it isn't exactly what we were looking for. What went
wrong on Windows? It turns out that the second parameter of String.replaceAll is a not an
ordinary string but a replacement string , as defined in the java.util.regex specification [Java-
API] . A backslash appearing in a replacement string escapes the following character, causing it to
be treated literally. When you run the program on Windows, the replacement string is a lone
backslash character, which is invalid. Admittedly, the exception could be a little more informative.
So how do you solve this problem? Release 5.0 provides not one but two new methods that solve it.
One is java.util.regex.Matcher.quoteReplacement , which translates a string into the
corresponding replacement string. Here is how to fix the program by using this method:
System.out.println(MeToo.class.getName().replaceAll(
"\\.", Matcher.quoteReplacement(File.separator) )
+ ".class");
The second method introduced in release 5.0 provides an even better solution. This method,
String.replace(CharSequence, CharSequence) , does the same thing as String.replaceAll , but
treats both the pattern and the replacement as literal strings. Here is how to fix the program by using
this method:
System.out.println(MeToo.class.getName().
replace(".", File.separator) + ".class");
But what if you are using an earlier Java release? Unfortunately, there is no easy way to generate
the replacement string. It is easier to dispense with regular expressions entirely and to use
String.replace(char, char) :
System.out.println(MeToo.class.getName().
 
 
Search WWH ::




Custom Search