-2

I know that backslashes are used for character escapes, so I have to use two of them to write a single backslash.

But why doesn't this compile?

"\\" => doesn't compile

BUT this:

"\\\\" => "\"

Which \ escapes what?

Thank you in advance!

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
Quaffel
  • 1,463
  • 9
  • 19
  • 2
    `String r = "\\";` compiles fine. And please format your question correctly to avoid escape issues here, since you've actually said `"\\\\" => doesn't compile` (which is also incorrect). – Tom Nov 07 '17 at 13:24
  • This is not true. Put full code and (potential) error message – Jacek Cz Nov 07 '17 at 13:25
  • 4
    Possible duplicate of [Why String.replaceAll() in java requires 4 slashes "\\\\" in regex to actually replace "\"?](https://stackoverflow.com/questions/18875852/why-string-replaceall-in-java-requires-4-slashes-in-regex-to-actually-r) – Tom Nov 07 '17 at 13:26
  • Yes, it is as I found out. (Explanation: 4th comment of answer one) – Quaffel Nov 07 '17 at 14:00

1 Answers1

5

This depends on the context. Some String methods don't use normal strings, they use regular expressions. In regular expressions, \ is an escape character too, so to have a regular expression that corresponds to the plain \ character, you have to write "\\\\".

Piotr Wilkin
  • 3,446
  • 10
  • 18
  • assumption goes too far. Nothing in question suggest such scenario – Jacek Cz Nov 07 '17 at 13:27
  • 1
    "\\" => doesn't compile - pretty much suggest the context. – kaos Nov 07 '17 at 13:38
  • 1
    Correct me if I am wrong, but it will compile, it will throw an exception at runtime when it will parse that regular expression but it will compile. – AxelH Nov 07 '17 at 13:44
  • 1
    But the error message it will throw is actually that it can't compile the regular expression (because regular expression functions don't really directly process the expressions, they internally call `Pattern::compile()`), hence the confusion. – Piotr Wilkin Nov 07 '17 at 13:53
  • 1
    Well, my IDE gave me a very uncomprehensive error, so i didn't associate it with with a syntatical error in Regular Expressions but (wrongly) with a language error. Therefore I assumed that it won't compile as my IDE didn't let me compile it. But yes, I used it in String#replace, but I didn't know that this was important, so i left it out. – Quaffel Nov 07 '17 at 13:57