Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eight backslashes required to replace single backslash with double backslashes?

Tags:

java

string

regex

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.

like image 683
John Fitzpatrick Avatar asked Oct 14 '11 11:10

John Fitzpatrick


1 Answers

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; see Matcher.replaceAll. Use Matcher.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(...)

like image 173
Bart Kiers Avatar answered Oct 21 '22 09:10

Bart Kiers