[英]java string split based on new line
I have following string 我有以下字符串
String str="aaaaaaaaa\n\n\nbbbbbbbbbbb\n \n";
I want to break it on \\n
so at the end i should two string aaaaaaaa
and bbbbbbbb
. 我想在
\\n
上将其断开,所以最后我应该输入两个字符串aaaaaaaa
和bbbbbbbb
。 I dont want last one as it only contain white space. 我不要最后一个,因为它只包含空白。 so if i split it based on new line character using
str.split()
final array should have two entry only. 因此,如果我使用
str.split()
根据换行符将其拆分,则最终数组应该只有两个条目。
I tried below: 我在下面尝试过:
String str="aaaaaaaaa\n\n\nbbbbbbbbbbb\n \n".replaceAll("\\s+", " ");
String[] split = str.split("\n+");
it ignore all \\n
and give single string aaaaaaaaaa bbbbbbbb
. 它忽略所有
\\n
并给出单个字符串aaaaaaaaaa bbbbbbbb
。
Delete the call to replaceAll()
, which is removing the newlines too. 删除对
replaceAll()
的调用,该调用也将删除换行符。 Just this will do: 只需这样做:
String[] split = str.split("\n\\s*");
This will not split on just spaces - the split must start at a newline (followed by optional further whitespace). 这不会仅在空格上分割-分割必须以换行符开头(随后是可选的其他空格)。
Here's some test code using your sample input with edge case enhancement: 这是一些使用示例输入和边缘案例增强功能的测试代码:
String str = "aaaaaaaaa\nbbbbbb bbbbb\n \n";
String[] split = str.split("\n\\s*");
System.out.println(Arrays.toString(split));
Output: 输出:
[aaaaaaaaa, bbbbbb bbbbb]
This should do the trick: 这应该可以解决问题:
String str="aaaaaaaaa\n\n\nbbbbbbbbbbb\n \n";
String[] lines = str.split("\\s*\n\\s*");
It will also remove all trailing and leading whitespace from all lines. 它还将从所有行中删除所有尾随和前导空格。
\\ ns被您的第一条语句删除:\\ s匹配\\ n
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.