String Split
split breaks a string into an array of substrings wherever a delimiter appears. It is how Java programs read comma-separated values, parse key=value settings, break sentences into words, and separate the parts of dates, paths, and version numbers. The method is simple to call, but its delimiter is a regular expression and its handling of empty fields follows specific rules, both of which are worth understanding precisely.
Basic Use
String csv = "red,green,blue";
String[] colors = csv.split(",");
System.out.println(colors.length); // 3
System.out.println(colors[0]); // red
System.out.println(Arrays.toString(colors)); // [red, green, blue]
The delimiter itself is removed; only the text between delimiters is returned. If the delimiter does not appear, the result is a one-element array containing the whole string.
The Delimiter Is a Regular Expression
split(regex) interprets its argument as a regex, so characters with special meaning in regular expressions must be escaped:
"1.2.3".split("."); // [] "." matches every character
"1.2.3".split("\\."); // [1, 2, 3] escaped dot
"a|b".split("\\|"); // [a, b] | means "or" in a regex
"a|b".split(Pattern.quote("|")); // [a, b] quote treats the text literally
Characters that need escaping include . $ | ( ) [ ] { } ^ ? * + 0 . Pattern.quote(text)` is the safest choice when the delimiter comes from a variable.
Being a regex is also an advantage: one call can split on several delimiters or on variable amounts of whitespace:
" ada king lovelace ".strip().split("\\s+"); // [ada, king, lovelace]
"a, b ;c".split("\\s*[,;]\\s*"); // [a, b, c] comma or semicolon, trimming spaces