我有文本区域,我正在尝试处理其中的文本以删除多个新行,特别是如果超过 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?
最佳答案
您可以使用正则表达式。例如:
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);
关于java - 从字符串中删除多个新行 (/r/n),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19643805/