有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从字符串中删除多个新行(/r/n)

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

为什么?

我甚至在查看十六进制代码时看到被替换的字符串 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) 个答案

  1. # 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);