我按空格分割字符串,但由于某种原因,新行字符被删除。例如:
String[] splitSentence = "Example sentence\n\n This sentence is an example".
split("\\s+");
splitSentence将包含此内容:
["Example", "sentence", "This", "sentence", "is", "an", "example"]
如果我这样做:
String[] splitSentence = "Example sentence\n\n This sentence is an example".
split("\\s");
splitSentence将包含此内容:
["Example", "sentence", "", "", "This", "sentence", "is", "an", "example"]
我试图达到这样的目标:
["Example", "sentence\n\n", "This", "sentence", "is", "an", "example"]
或者像这样:
["Example", "sentence", "\n", "\n", "This", "sentence", "is", "an", "example"]
我尝试过很多没有运气的事情......任何帮助都会受到赞赏。
答案 0 :(得分:2)
String[] splitSentence = "Example sentence\n\n This sentence is an example".
split(' ');
这个版本应该可以工作,所以空白区域只会删除而不是新行。
答案 1 :(得分:1)
按空格和标签分割(不带换行符):
String[] splitSentence = "Example sentence\n\n This sentence is an example".split("[ \t]+");
结果:["Example", "sentence\n\n", "This", "sentence", "is", "an", "example"]
答案 2 :(得分:1)
在正则表达式中,\s
被定义为等同于此集合中的字符:
[ \t\n\x0B\f\r]
(见javadoc)。如果您不希望换行符被视为空格,那么您可以编写自己的集合:
splitSentence = "Example sentence\n\n This sentence is an example".split("[ \t\\x0B\f\r]+");
(或删除您不希望split
识别的其他字符。)
(\t
是TAB,\x0B
是垂直制表符,\f
是FF(换页),\r
是CR)
编辑:此方法似乎产生了您提到的第二个结果,其中\n
作为单独的字符串返回:
splitSentence = "Example sentence\n\n This sentence is an example".split("[ \t\\x0B\f\r]+|(?=\n)");
这使用预测功能在\n
后面的某个点进行拆分,但不会将\n
视为将从结果中删除的分隔符。