Home >Java >javaTutorial >How to Split a Java String Using All Whitespace Characters as Delimiters?
Splitting a String using Whitespace Delimiters in Java
Java's String class provides a powerful 'split()' method for dividing strings into substrings. However, what if you need to delineate strings using all whitespace characters, including spaces, tabs, and newlines?
Regex for Whitespace Delimiters
The regex pattern to pass to 'split()' for this purpose is 's '. This pattern encompasses all characters defined as whitespace, ensuring a consistent split on any white space.
Applying the Pattern
To apply the pattern, simply use the following syntax:
String[] substrings = myString.split("\s+");
This will split 'myString' into an array of substrings, where each substring is separated by any amount of whitespace.
Example
Consider the string:
"Hello [space character] [tab character] World"
Using the provided regex, the split operation would yield the following substrings:
Note that the empty space between the [space] and [tab] characters is omitted from the result.
Escape Considerations
As VonC mentions, the backslash character in the regex must be escaped in Java. This prevents Java from attempting to escape the string as a特殊 character. To pass the literal 's', use 's' instead.
Equivalent RegEx
The 's' pattern is equivalent to the following character class:
[ \t\n\x0B\f\r]
This class includes all whitespace characters defined by Java's Character class.
The above is the detailed content of How to Split a Java String Using All Whitespace Characters as Delimiters?. For more information, please follow other related articles on the PHP Chinese website!