Mladen Adamovic
Mladen Adamovic

Reputation: 3201

Removing multiple new lines (/r/n) from String

I have textarea and I'm trying to process the text from it to remove multiple new lines, specifically if more than 2 new lines into maximum 2 new lines. But somehow String.replace("\r\n\r\n\r\n", "\r\n\r\n") doesn't seems to work.

Why?

I even see the replaced string when I look into it Hex code many 0d0a0d0a0d0a0d0a0d

For the reference this is the method what I'm using:

public static String formatCommentTextAsProvidedFromUser(String commentText) {
  commentText = commentText.trim();
  commentText = commentText.replace("\n\n\n", "\n\n");
  commentText = commentText.replace("\r\n\r\n\r\n", "\r\n\r\n");
  try {
    Logger.getLogger(CommonHtmlUtils.class.getName()).info("Formated = "  + String.format("%040x", new BigInteger(1, commentText.getBytes("UTF-8"))));
  } catch (UnsupportedEncodingException ex) {
    Logger.getLogger(CommonHtmlUtils.class.getName()).log(Level.SEVERE, null, ex);
  }
  return commentText;
}

I'm confused. Why 0a 0d multiple times after replace?

Upvotes: 0

Views: 3561

Answers (1)

Paul Vargas
Paul Vargas

Reputation: 42020

You can use a regular expression. e.g.:

commentText = commentText.replaceAll("(\r?\n){3,}", "\r\n\r\n");

This replace 3 o more newlines into 2 newlines.

In another way, you may want to use the default system line separator:

String lineSeparator = System.getProperty("line.separator");

So,

commentText = commentText.replaceAll("(\r?\n){3,}", 
                                      lineSeparator + lineSeparator);

Upvotes: 1

Related Questions