How to replace the characher `\n` as a new line in android

user4260260 picture user4260260 · Dec 22, 2015 · Viewed 9.4k times · Source

I have one server response for an API request as shown below.

Success! Your request has been sent.\n\nWe’ll inform you once it is done.

This message I need to show in a Snackbar. I need new line to be added in the place of \n in this response . I tried by using replaceAll like

String message = (serverResponse.getMessage()).replaceAll("\\n", System.getProperty("line.separator"));

but it is showing like this

enter image description here

Same message if I add in string.xml resource file and get using getString(R.string.message) then the \n is working properly. How can I get a new line from this response string?

I tried changing \n with other character like <new_line> from server response and it is working fine with replaceAll. Problem is only with \n in response message. Is there any way to parse \n?

Answer

Dalija Prasnikar picture Dalija Prasnikar · Dec 22, 2015

What you need is

String message = serverResponse.getMessage().replaceAll("\\\\n", "\n");

Why four backslashes are needed?

Because in Java backslash \ is escape character. If you want to have single backslash literal inside Java string you have to escape it and use \\

But, replaceAll method expects regex expression, where again backslash is escape character so you need to escape it, too.

Basically, in above code Java string parser will first convert those four backslashes to two \\\\ -> \\ and then regex parser will interpret remaining two backslashes as single backslash literal.