按空格分割字符串会删除换行符

时间:2014-07-15 01:34:35

标签: java android regex string

我按空格分割字符串,但由于某种原因,新行字符被删除。例如:

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"]

我尝试过很多没有运气的事情......任何帮助都会受到赞赏。

3 个答案:

答案 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视为将从结果中删除的分隔符。