Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace \n and \r\n with <br /> in java

This has been asked several times for several languages but I can't get it to work. I have a string like this

String str = "This is a string.\nThis is a long string."; 

And I'm trying to replace the \n with <br /> using

str = str.replaceAll("(\r\n|\n)", "<br />"); 

but the \n is not getting replaced. I tried to use this RegEx Tool to verify and I see the same result. The input string does not have a match for "(\r\n|\n)". What am i doing wrong ?

like image 254
Bala R Avatar asked Jun 16 '10 20:06

Bala R


People also ask

How do you replace a line break in Java?

In order to replace all line breaks from strings replace() function can be used. String replace(): This method returns a new String object that contains the same sequence of characters as the original string, but with a given character replaced by another given character.

How do you replace new line and space in a string in Java?

L. replaceAll("[\\\t|\\\n|\\\r]","\\\s");

How do you use BR in Java?

Replace new line (\n) with HTML br tag in string using Javauses the \n character, also known as Line Feed (LF) character, to move the cursor to the next line. Windows uses \r\n characters to specify the start of the line, sometimes also called Carriage Return and Line Feed (CRLF).


2 Answers

It works for me.

public class Program {     public static void main(String[] args) {         String str = "This is a string.\nThis is a long string.";         str = str.replaceAll("(\r\n|\n)", "<br />");         System.out.println(str);     } } 

Result:

 This is a string.<br />This is a long string. 

Your problem is somewhere else.

like image 84
Mark Byers Avatar answered Sep 18 '22 13:09

Mark Byers


A little more robust version of what you're attempting:

str = str.replaceAll("(\r\n|\n\r|\r|\n)", "<br />"); 
like image 27
Dolph Avatar answered Sep 17 '22 13:09

Dolph