2

Currently I am showing messages that I get from DB using only these two replacements:

text = text.replace("\r\n", "<br />");
text = text.replace("\n", "<br />");

but the problem is if there are many consecutive "\n"s I will have lots of
s or white spaces, I just want to make them all one. So what is your suggestion? Is there a quick replace method to make all consecutive \n\n\n\n\n\n\n only one just one br?

Jimmy Page
  • 343
  • 1
  • 6
  • 12

3 Answers3

6

You can use quantifier + to denote 1 or more.. Also, * means 0 or more..

text = text.replaceAll("\n+", "<br />");

text = text.replaceAll("[\n\r]+", "<br />");
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
2

If you have multiple \r\n or \n with other content in between, you may also use

text.replaceAll("(\r\n)+", "<br />")
    .replaceAll("\n+", "<br />");
Cory Kendall
  • 7,195
  • 8
  • 37
  • 64
1

Have you tried this:

text = text.replace("(\r\n)+", "<br />");
text = text.replace("\n+", "<br />");

The + means "one or more" of the preceding match.

gpojd
  • 22,558
  • 8
  • 42
  • 71