split method Null safety

List<String> split(
  1. Pattern pattern

Splits the string at matches of pattern and returns a list of substrings.

Finds all the matches of pattern in this string, as by using Pattern.allMatches, and returns the list of the substrings between the matches, before the first match, and after the last match.

var string = "Hello world!";
string.split(" ");                      // ["Hello", "world!"];

If the pattern doesn't match this string at all, the result is always a list containing only the original string.

If the pattern is a String, then it's always the case that:

string.split(pattern).join(pattern) == string

If the first match is an empty match at the start of the string, the empty substring before it is not included in the result. If the last match is an empty match at the end of the string, the empty substring after it is not included in the result. If a match is empty, and it immediately follows a previous match (it starts at the position where the previous match ended), then the empty substring between the two matches is not included in the result.

var string = "abba";
var re = RegExp(r"b*");
// re.allMatches(string) will find four matches:
// * empty match before first "a".
// * match of "bb"
// * empty match after "bb", before second "a"
// * empty match after second "a".
print(string.split(re));  // ["a", "a"]

A non-empty match at the start or end of the string, or after another match, is not treated specially, and will introduce empty substrings in the result:

var string = "abbaa";
string.split("a"); // ["", "bb", "", ""]

If this string is the empty string, the result is an empty list if pattern matches the empty string, since the empty string before and after the first-and-last empty match are not included. (It is still a list containing the original empty string [""] if the pattern doesn't match).

var string = "";
string.split("");                       // []
string.split("a");                      // [""]

Splitting with an empty pattern splits the string into single-code unit strings.

var string = "Pub";
string.split("");                       // ["P", "u", "b"]
// Same as:
[for (var unit in string.codeUnits)
    String.fromCharCode(unit)]          // ["P", "u", "b"]

Splitting happens at UTF-16 code unit boundaries, and not at rune (Unicode code point) boundaries:

// String made up of two code units, but one rune.
string = '\u{1D11E}';
string.split('')  // ["\ud834", "\udd1e"] - 2 unpaired surrogate values

To get a list of strings containing the individual runes of a string, you should not use split. You can instead get a string for each rune as follows:

[for (var run in string.runes) String.fromCharCode(rune)]


List<String> split(Pattern pattern);