Java Pattern split() Method
Example
Split a text at each comma, together with any spaces after the comma:
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile(",\\s*");
String[] cars = pattern.split("Volvo,BMW, Ford, Mazda");
for (String car : cars) {
System.out.println(car);
}
}
}
Definition and Usage
The split() method splits a text into an array of parts. The text is split at each place where the pattern matches.
In the example, the regular expression ,\s* means "a comma, followed by zero or more whitespace characters (spaces, tabs or line breaks)". \s means one whitespace character, and * means "zero or more times". In a Java string, you must write the backslash two times: ",\\s*".
Tip: The split() method of the String class works the same way: text.split(",\\s*").
Syntax
One of the following:
public String[] split(CharSequence input)
public String[] split(CharSequence input, int limit)
Parameter Values
| Parameter | Description |
|---|---|
| input | Required. The text to split. |
| limit | Optional. The largest number of parts in the array. If it is 0 or left out, the text is split at every match, and empty parts at the end are removed. If it is negative, the text is split at every match, and empty parts at the end are kept. |
Technical Details
| Returns: | A String[] array with the parts of the text. |
|---|
Related Pages
❮ RegEx Methods