java – How to split a string with any whitespace chars as delimiters

java – How to split a string with any whitespace chars as delimiters

Something in the lines of

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

In most regex dialects there are a set of convenient character summaries you can use for this kind of thing – these are good ones to remember:

w – Matches any word character.

W – Matches any nonword character.

s – Matches any white-space character.

S – Matches anything but white-space characters.

d – Matches any digit.

D – Matches anything except digits.

A search for Regex Cheatsheets should reward you with a whole lot of useful summaries.

java – How to split a string with any whitespace chars as delimiters

To get this working in Javascript, I had to do the following:

myString.split(/s+/g)