tags:

views:

37

answers:

2

I want to macth the following:

boolean b = "\u000D".matches("\\cM");

but the compiler give me:

unclosed string literal
illegal character: \92
illegal character: \92
unclosed string literal
not a statement

why? that literal is not a valid unicode Ctrl-m unicode code???

+3  A: 

The problem of unclosed string literal is because the \uXXXX sequences are resolved before lexing. So

boolean b = "\u000D".matches("\\cM");

becomes

boolean b = "
".matches("\\cM");

which is invalid Java code. (yes it also means you could write String foo = \u0022\u0021\u0022; and compiles correctly.)

If you write instead

boolean b = "\r".matches("\\cM"); // \r == \u000D

then the code works and return true.

KennyTM
+1  A: 

Haha !

This is a trap!

Java processes Unicode escapes before interpretation. So, it converts you code into:

boolean b = "
".matches("\\cM"); 

.. and so, it is definitely an error - incompleted string and so on.

Nulldevice
Ups ! I have unswered simultaneously with other guy!
Nulldevice
Not simultaneously, you're 47 seconds slower :p
KennyTM
I swear that I have not looked at you solution :) Though you answer is more detailed.
Nulldevice