问题
I need to format text coming from user to HTML, but the input is multiple line and I have to replace all "enters" from that string to HTML <br />
tags.
String message = messageEditText.getText().toString();
This is the message I want to format. How can I format the string accordingly?
回答1:
try
message = message.replace ("\\r\\n", "<br>").replace ("\\n", "<br>");
回答2:
You can use the double replacement as already suggested in other responses, but I would tend to prefer regex replacement, for concision of code:
yourString.replaceAll("\r?\n", "<br/>");
Or, of course Pattern equivalent, if you need to do the operation multiple times:
Pattern endOfLine = Pattern.compile("\r?\n");
endOfLine.matcher(yourString).replaceAll("<br/>");
Also, be careful with using System's line separator if user's input has been acquired from a web interface, or a remote system (depending on your use case, of course). User may use a different OS...
However, in all cases, make sure you do any EOL -> <br/> replacement, AFTER you have HTML-encoded any special characters in the user's input. Otherwise, the <br> tag will get encoded...
回答3:
According to your operating system, the string will have newline character/s at the end of each line. Those can be \n
or \r\n
. Just write:
inputString = inputString.replace("\r\n", "<br />").replace("\n", "<br />");
By this, if the current operating system uses \r\n
those will be replaced within the first replacement, else if it's \n
, they won't be found in first replacement, but will be replaced within the second one.
If you want to write some cool code, you can use the following:
System.getProperty("line.separator")
to get the new-line character/s of the system.
来源:https://stackoverflow.com/questions/26174622/android-format-string-to-html-add-new-lines-br