snippetjavaCritical
How to split a string with any whitespace chars as delimiters
Viewed 0 times
withhowwhitespacecharsanysplitdelimitersstring
Problem
What regex pattern would need I to pass to
java.lang.String.split() to split a String into an Array of substrings using all whitespace characters (' ', '\t', '\n', etc.) as delimiters?Solution
Something in the lines of
This groups all white spaces as a delimiter.
So if I have the string:
This should yield the strings
As VonC pointed out, the backslash should be escaped, because Java would first try to escape the string to a special character, and send that to be parsed. What you want, is the literal
The
myString.split("\\s+");This groups all white spaces as a delimiter.
So if I have the string:
"Hello[space character][tab character]World"This should yield the strings
"Hello" and "World" and omit the empty space between the [space] and the [tab].As VonC pointed out, the backslash should be escaped, because Java would first try to escape the string to a special character, and send that to be parsed. What you want, is the literal
"\s", which means, you need to pass "\\s". It can get a bit confusing.The
\\s is equivalent to [ \\t\\n\\x0B\\f\\r].Code Snippets
myString.split("\\s+");"Hello[space character][tab character]World"Context
Stack Overflow Q#225337, score: 1018
Revisions (0)
No revisions yet.