CKTIS / Java
String.split — splitting text with a regular expression
String.split returns an array of text fragments separated by regular-expression matches. The limit parameter controls the number of splits and the treatment of trailing empty elements.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
String[] parts = text.split(regex);
String[] parts = text.split(regex, limit);String.split returns a String[] in fragment order, excluding matched delimiters. With no match, the result contains one element: the entire input.
split(regex) means split(regex, 0): trailing empty elements are removed. A limit < 0 preserves them. A limit > 0 allows at most limit - 1 splits; the last element holds the remaining text, and the array has at most limit elements.
regex is a regular expression, not a plain delimiter. Write a literal dot as "\\."; protect an arbitrary literal delimiter with Pattern.quote(separator) from java.util.regex.Pattern. An invalid pattern throws PatternSyntaxException.
With limit == 1, no split occurs, even if the pattern matches at the start. When the method splits on a match that consumes characters at the start, it produces a leading empty element. A zero-width match at the start does not produce one. With limit == 0, if all elements produced by the split are empty, all of them are discarded, including the first. For example, ",".split(",", 0) returns an empty array.
Examples
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String text = "red.blue..";
System.out.println(Arrays.toString(text.split("\\.")));
System.out.println(Arrays.toString(text.split("\\.", -1)));
System.out.println(Arrays.toString(text.split("\\.", 2)));
}
}Result
[red, blue] [red, blue, , ] [red, blue..]
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.