我如何替换所有的换行符从一个字符串在Java在这样的方式,将工作在Windows和Linux(即没有具体的操作系统的回车/换行/新行等问题)?

我尝试过(注意readFileAsString是一个将文本文件读入String的函数):

String text = readFileAsString("textfile.txt");
text.replace("\n", "");

但这似乎并不奏效。

如何做到这一点呢?


当前回答

换行符在windows/linux/mac下是不一样的。你应该使用系统。使用属性line.separator获取properties。

其他回答

你需要将text设置为text.replace()的结果:

String text = readFileAsString("textfile.txt");
text = text.replace("\n", "").replace("\r", "");

这是必要的,因为字符串是不可变的——调用replace并不会改变原始的字符串,它会返回一个被改变的新字符串。如果不将结果赋值给文本,那么新的String将丢失并被垃圾收集。

至于为任何环境获取换行字符串——可以通过调用System.getProperty("line.separator")来获得。

如果你只想删除当前操作系统上有效的行结束符,你可以这样做:

text = text.replaceAll(System.getProperty("line.separator"), "");

如果你想确保你删除了任何行分隔符,你可以这样做:

text = text.replaceAll("\\r|\\n", "");

或者,稍微啰嗦一点,但不那么regexy:

text = text.replaceAll("\\r", "").replaceAll("\\n", "");

试着这样做:

 textValue= textValue.replaceAll("\n", "");
 textValue= textValue.replaceAll("\t", "");
 textValue= textValue.replaceAll("\\n", "");
 textValue= textValue.replaceAll("\\t", "");
 textValue= textValue.replaceAll("\r", "");
 textValue= textValue.replaceAll("\\r", "");
 textValue= textValue.replaceAll("\r\n", "");
 textValue= textValue.replaceAll("\\r\\n", "");

该函数将所有空格(包括换行符)归一化为单个空格。不完全是最初的问题所要求的,但在许多情况下可能恰恰是需要的:

import org.apache.commons.lang3.StringUtils;

final String cleansedString = StringUtils.normalizeSpace(rawString);

我想这是很有效的

String s;
s = "try this\n try me.";
s.replaceAll("[\\r\\n]+", "")