如何在Android中将characher`\n`替换为新行 [英] How to replace the characher `\n` as a new line in android
问题描述
我对一个API请求有一个服务器响应,如下所示。
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.
我需要在小吃栏中显示此消息。我需要在此响应中添加新行代替 \n
。我尝试使用 replaceAll
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"));
但它显示的是这样
如果我添加 string.xml
资源,则会出现相同的消息文件并使用 getString(R.string.message)
进行操作,则 \n
正常工作。如何从此响应字符串获取新行?
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?
我尝试将 \n
更改为其他字符,例如< new_line>
来自服务器响应,它与 replaceAll
正常工作。问题仅与响应消息中的 \n
有关。有什么方法可以解析 \n
?
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
?
推荐答案
您要做什么
字符串消息= serverResponse.getMessage()。replaceAll( \n, \n );
为什么需要四个反斜杠?
Why four backslashes are needed?
由于Java反斜杠 \
是转义符。如果要在Java字符串中包含单个反斜杠文字,则必须对其进行转义并使用 \\
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 \\
但是, replaceAll
方法要求使用正则表达式,其中反斜杠也是转义字符,因此您也需要对其进行转义。
But, replaceAll
method expects regex expression, where again backslash is escape character so you need to escape it, too.
基本上,在上面的代码中,Java字符串解析器首先会将这四个反斜杠转换为两个 \->。 \\
,然后正则表达式解析器会将其余的两个反斜杠解释为单个反斜杠文字。
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.
这篇关于如何在Android中将characher`\n`替换为新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!