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

7

74

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 ?

Bowne answered 16/6, 2010 at 20:12 Comment(4)
I also tried "(\\r\\n|\\n)"Bowne
Could you post a more complete example? I think the error is not in the code you posted.Ogdan
I pretty much have the same two lines and I was testing it in debug mode in eclipse with a break-point after replaceAll() .Bowne
[\r?\n] can also work.Gonzalogoo
O
124

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.

Ogdan answered 16/6, 2010 at 20:17 Comment(0)
Z
20

For me, this worked:

rawText.replaceAll("(\\\\r\\\\n|\\\\n)", "\\\n");

Tip: use regex tester for quick testing without compiling in your environment

Zachariahzacharias answered 21/8, 2012 at 11:0 Comment(3)
I don't think you have enough backslashes there :)Bikini
I had the same problem. Thing was the output was showing "\n" but for this to work, it was a string of "\\\\n" wich the output resulted as "\n", hence the wrong interpretation :)Soracco
You need to use this code: rawText.replaceAll("(\\\\r\\\\n|\\\\n)", "\\\\n");Oquassa
H
19

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

str = str.replaceAll("(\r\n|\n\r|\r|\n)", "<br />");
Hydantoin answered 16/6, 2010 at 20:18 Comment(1)
There's no need to do the more lengthy method. String's replaceAll(...) does exactly that behind the scenes. This is its method body: return Pattern.compile(expr).matcher(this).replaceAll(substitute): docjar.com/html/api/java/lang/String.java.htmlContrive
C
11

Since my account is new I can't up-vote Nino van Hooff's answer. If your strings are coming from a Windows based source such as an aspx based server, this solution does work:

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

Seems to be a weird character set issue as the double back-slashes are being interpreted as single slash escape characters. Hence the need for the quadruple slashes above.

Again, under most circumstances "(\\r\\n|\\n)" should work, but if your strings are coming from a Windows based source try the above.

Just an FYI tried everything to correct the issue I was having replacing those line endings. Thought at first was failed conversion from Windows-1252 to UTF-8. But that didn't working either. This solution is what finally did the trick. :)

Conclusion answered 2/7, 2014 at 17:29 Comment(0)
K
2

It works for me. The Java code works exactly as you wrote it. In the tester, the input string should be:

This is a string.
This is a long string.

...with a real linefeed. You can't use:

This is a string.\nThis is a long string.

...because it treats \n as the literal sequence backslash 'n'.

Kailyard answered 16/6, 2010 at 20:40 Comment(0)
B
0

That should work, but don't kill yourself trying to figure it out. Just use 2 passes.

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

Disclaimer: this is not very efficient.

Boaten answered 16/6, 2010 at 20:14 Comment(3)
If you're going to do two replacements, then regex is not needed and one could simply do: str = str.replace("\r\n", "<br />").replace("\n", "<br />");Contrive
@BartK I don't think there is a replace(String,String) in String class. I was only able to find replace(Char, Char)Bowne
@Bala correct, there is no such method. But there is a replace(CharSequence, CharSequence). Note that String is a CharSequence.Contrive
S
-2

This should work. You need to put in two slashes

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

In this Reference, there is an example which shows

private final String REGEX = "\\d"; // a single digit

I have used two slashes in many of my projects and it seems to work fine!

Sixth answered 16/6, 2010 at 20:15 Comment(4)
Actually you don't need two slashes.Ogdan
not sure what your reference has to do with the rest of your answer. The part "You need to put in two slashes" is even plain wrong, to be honest.Contrive
like I said: both work (neither did Mark say your suggestion did not work, you just don't need the two backslashes: one will do). The point is: your comment that is needs two back slashes (opposed to just one) is still wrong. And \\d inside a string literal becomes \d while \n inside a string literal is still just \n (a line break), in other words: you can't compare the two.Contrive
I see you removed all of your comments, which leads me to believe you understand my remarks. I suggest you remove your answer as well since the majority of your answer in not correct (don't worry, you won't loose your points by doing so). If you leave it out here (with the incorrect claims), it is likely it will draw more down-votes.Contrive

© 2022 - 2024 — McMap. All rights reserved.