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.
–
(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.