This is a "what the heck is going on here" question. I don't actually need a solution.
I had to replace all single backslashes in a String with double backslashes . This is what I ended up doing...
strRootDirectory = strRootDirectory.replaceAll("\\\\", "\\\\\\\\");
...where strRootDirectory is a java.lang.String above.
Now, I understand the four backslashes for the first argument: regex expects two backslashes in order to indicate a single literal backslash, and java wants them doubled up. That's fine.
BUT, what the heck is going on with the eight backslashes for the second argument? Isn't the replacement string supposed to be a literal (non-regex, I mean) string? I expected to need four backslashes in the second argument, in order to represent two backslashes.
The second argument isn't a regex-string, but a regex-replacement-string, in which the backslash also has a special meaning (it is used to escape the special character $
used for variable interpolation and is also used to escape itself).
From The API:
Note that backslashes (
\
) and dollar signs ($
) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; seeMatcher.replaceAll
. UseMatcher.quoteReplacement(java.lang.String)
to suppress the special meaning of these characters, if desired.-- http://download.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With