Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (10.2k points)

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?

1 Answer

0 votes
by (46k points)

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

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]

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...