Are eight backslashes required to replace a single backslash with a double backslash?

This is the question "what the hell is here." I really don't need a solution.

I had to replace all single backslashes in String with double backslashes. This is what I ended up doing ...

strRootDirectory = strRootDirectory.replaceAll("\\\\", "\\\\\\\\");

... where strRootDirectory is java.lang.String above.

Now I understand four backslashes for the first argument: the regular expression expects two backslashes to indicate a single backslash, and java wants them to double. It's fine.

BUT, what the hell happens with eight backslashes for the second argument? Shouldn't a replacement string be a literal (non-regular, I mean) string? I expected that in the second argument, four backslashes would be required to represent two backslashes.

+5
source share
6 answers

The second argument is not a regular string, but a regular expression string in which the backslash also has special meaning (it is used to exit the special character $used for the interpolation variable, and also used to save itself).

From the API:

, (\) ($) , , ; . Matcher.replaceAll. Matcher.quoteReplacement(java.lang.String) , .

- http://download.oracle.com/javase/6/docs/api/java/lang/String.html#replaceAll (...)

+8

, replace("\\","\\\\") (String.replace , )

Pattern.quote Matcher.quoteReplacement

+6

"\\\\\\\\" 4 : \\\\. , - , .

+2

Java, replaceAll escape-. , . , , , escape-, .

+1

, , , .

, , , , , .

  • 1 .
  • .
  • .
  • , .

8.

+1

... :

System.out.println( "line1: "+"hello\\\\world" );
System.out.println( "line2: "+"hello\\\\world".replaceAll("\\\\\\\\", Matcher.quoteReplacement("\\") ) );

line1: hello\\world
line2: hello\world

, ...

+1

All Articles