从String中删除多个新行(/ r / n)

时间:2013-10-28 19:49:29

标签: java html-parsing special-characters

我有textarea,我正在尝试处理它的文本以删除多个新行,特别是如果超过2个新行最多2个新行。 但不知怎的String.replace("\r\n\r\n\r\n", "\r\n\r\n")似乎没有用。

为什么?

当我查看Hex代码时,我甚至会看到替换后的字符串 0d0a0d0a0d0a0d0a0d

作为参考,这是我正在使用的方法:

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;
}

我很困惑。为什么在替换后多次0a 0d?

1 个答案:

答案 0 :(得分:1)

您可以使用正则表达式。 e.g:

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

将3个以上换行符替换为2个换行符。

另一方面,您可能希望使用默认的系统行分隔符:

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

所以,

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