我想在Java中从我的字符串中拆分/ n。例如,我有一个String字段,其中有2行空格(/ n)。我必须找出线(mopre比一条线要到的地方)并且应该用一个线空格替换。
"This is Test Message
thanks
Zubair
"
从上面的例子中,“This is Test Message”和“thanks”之间有更多的空格。所以我想减少只有一行而不是2行。怎么做?
答案 0 :(得分:4)
str.replaceAll("(\\r\\n?|\\n){3,}", "$1$1");
这样做是用两个行终止符替换三个或更多行终止符(\r
,\n
或\r\n
),因此任何双空行都会替换为一个空行,如果我明白你的想法。
答案 1 :(得分:2)
我不知道如何使用正则表达式,但你可以使用StringTokenizer:
String reduceToOneLine(String input){
// Note that this means both \r and \n are tokens, not that they have to appear together.
StringTokenizer tokenizer = new StringTokenizer(input, "\r\n");
StringBuffer output = new StringBuffer();
while(tokenizer.hasMoreTokens()){
output.append(tokenizer.nextToken());
}
return output.toString();
}
这会在换行符上拆分字符串,然后将每一行添加到一个新字符串中(标记生成器将其分隔符的倍数视为一个,因此在行之间只留下一个换行符。)