New string character representation in Java

I have a field in a database that looks like

abcd.\nefgh

      

On the Java side, I am getting it into a variable (message) and I need to split this variable into two parts, the first and the second.

Something like that:

message="abcd.\nefgh" ;//This is not what happens ???
first = //Anything before '\n'
second = //Anything after '\n'

      

I tried the following

if(message.indexOf('\n')>-1){
  first = message.substring(0, message.indexOf('\n'));
  second = message.substring(message.indexOf('\n')) ;
}

      

However, my code never goes into the body of the if statement. I checked with a debugger and it shows that my message variable is indeed

abcd.\\nefgh

      

So, I tried this using the String.split method,

String rabit = "Abcd\\nEfgh" ;
System.out.println("Results \n "+  rabit.split("\n")) ; //1
//and alternative
System.out.println("Results \n "+  rabit.split("\\n")) ; //2

      

However, here's the problem. In both 1 and 2 outputs, I get an array with only one element. - complete message. Template not found.

So, can anyone help - what is the problem? The fact that my variable message comes from the database with \ n? Any other suggestions? How can I solve this?

+3


source to share


1 answer


If the string contains a literal \n

, then you need four escape characters in the regex split

:



rabit.split("\\\\n")

      

+9


source







All Articles