Reputation:
I would like to split a string by two delimeters: a space (" ") or a new line (\n).
What I've tried:
message.split("\\r?\\n? ");
It does split by space, but not by \n, turning:
The way I see it we got two options. Option one, we take the easy way
out. It's quick and painless. I'm not a fan of option one. Option two,
We fight.
into:
[The, way, I, see, it, we, got, two, options., Option, one,, we, take, the, easy, way, out., It's, quick, and, painless., I'm, not, a, fan, of, option, one.Option, two,, We, fight.]
Note that one.Option
is one cell in the array.
Upvotes: 0
Views: 836
Reputation: 164766
From the comments, try "\\s+"
to split on one or more whitespace characters. This includes space, tab, newline, carriage-return, line-feed, etc so it might be a bit too large a hammer for what you want.
final String message = "The way I see it we got two options. Option one, we take the easy way\n" +
"out. It's quick and painless. I'm not a fan of option one. Option two,\n" +
"We fight.";
System.out.println(String.join(", ", message.split("\\s+")));
Produces
The, way, I, see, it, we, got, two, options., Option, one,, we, take, the, easy, way, out., It's, quick, and, painless., I'm, not, a, fan, of, option, one., Option, two,, We, fight.
Upvotes: 1
Reputation: 8598
"\\r?\\n? "
This tells it to split by either "\\r\\n "
or "\\n "
or "\\r "
or " "
, but never by "\\r"
or "\\n"
or "\\r\\n"
without the space.
The following will tell it to split by any consecutive combination of "\\r"
, "\\n"
and " "
with at least one character:
"[\\r\\n ]+"
Upvotes: 2