How do I split a string with any whitespace chars as delimiters?

791    Asked by RishabhDwivedi in Devops , Asked on Jul 18, 2021
: What regex pattern would need I to pass to the java.lang.String.split() method to split a String into an Array of substrings using all whitespace characters (' ', 't', 'n', etc.) as delimiters? How did java split on whitespace?


Answered by Jack GREEN

For split on whitespace in JavaTry this syntax:

      myString.split("\s+");

This combines all-white spaces as a delimiter.

So if you have the string:

      "Hello[space][tab]World"

This will yield the strings "Hello" and "World" and eliminate the space among the [space] and the [tab].

Note: The backslash should be avoided because Java would first try to avoid the string to a special character, and transfer that to be parsed. What you want, is the literal "s", which means, you need to pass "\s". It can become a bit complicated.

      The \s is equivalent to [ \t\n\x0B\f\r]


Your Answer

Interviews

Parent Categories