What regex pattern would need to pass to the java.lang.String.split() method to split a string with all whitespace characters (' ', '\t', '\n', etc.) as delimiters?
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.
Something in the lines of
myString.split("\\s+");
this groups all whitespaces as a delimiter... so if i have the string "Hello[space][tab]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]
Perhaps a gentle reminder to RTFM ... java is one of the best-documented languages on the web; learning to navigate online docs will save you oodles of time on questions like this.
http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html
Good luck!
Update for those who downvoted:
I'd appreciate your comments as to why this isn't helpful. Is it because this answer requires the OP to put a bit of personal effort into solving his or her own problem, rather than simply spoon-feeding the answer? Consider:
- Rather than providing a partial answer, the link is a one-click all-inclusive solution.
- Not only is the original question answered, but the OP now has the tools to become self-sufficient.
- The ability to find answers, quickly and independently, to a wide variety or problems is far more valuable than asking for help every step of the way -- which type of person would you hire?