添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
深沉的野马  ·  JavaIO流 ...·  昨天    · 
捣蛋的牙膏  ·  java ...·  昨天    · 
霸气的跑步机  ·  Strings with ...·  昨天    · 
谦和的沙滩裤  ·  主题配置 | ...·  昨天    · 
活泼的签字笔  ·  About the output ...·  8 月前    · 
机灵的皮带  ·  token --- ...·  1 年前    · 
玉树临风的山羊  ·  Amazon ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm splitting a string by whitespaces, but for some reason the new line characters are being removed. For example:

String[] splitSentence = "Example sentence\n\n This sentence is an example".
   split("\\s+");

splitSentence will contain this:

["Example", "sentence", "This", "sentence", "is", "an", "example"]

and if I make this:

String[] splitSentence = "Example sentence\n\n This sentence is an example".
   split("\\s");

splitSentence will contain this:

["Example", "sentence", "", "", "This", "sentence", "is", "an", "example"]

I'm trying to achieve something like this:

["Example", "sentence\n\n", "This", "sentence", "is", "an", "example"]  

Or like this:

["Example", "sentence", "\n", "\n", "This", "sentence", "is", "an", "example"]

I've tried a lot of things with no luck... Any help will be appreciated.

If you want to exclude the newline from \s then use the inverse of the inverse and add \n like this [^\S\n] – HamZa Jul 15, 2014 at 1:39

(See the javadoc). If you don't want newlines to be treated like spaces, then you can write your own set:

splitSentence = "Example sentence\n\n This sentence is an example".split("[ \t\\x0B\f\r]+");

(or eliminate other characters you don't want the split to recognize).

(\t is TAB, \x0B is vertical tab, \f is FF (form feed), \r is CR)

EDIT: This method seems to produce the second result you mentioned, where the \n's are returned as separate strings:

splitSentence = "Example sentence\n\n This sentence is an example".split("[ \t\\x0B\f\r]+|(?=\n)");

This uses lookahead to split at a point that is immediately followed by \n, but doesn't treat \n as a delimiter that will be removed from the result.

Split by spaces and tabs (without newline):

String[] splitSentence = "Example sentence\n\n This sentence is an example".split("[ \t]+");

Result: ["Example", "sentence\n\n", "This", "sentence", "is", "an", "example"]

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.