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 ?
For me, this worked:
Tip: use regex tester for quick testing without compiling in your environment
It works for me.
Result:
Your problem is somewhere else.
A little more robust version of what you're attempting:
It works for me. The Java code works exactly as you wrote it. In the tester, the input string should be:
...with a real linefeed. You can't use:
...because it treats
\n
as the literal sequence backslash 'n'.That should work, but don't kill yourself trying to figure it out. Just use 2 passes.
Disclaimer: this is not very efficient.
This should work. You need to put in two slashes
In this Reference, there is an example which shows
I have used two slashes in many of my projects and it seems to work fine!