split method

List<String> split(
  1. String text, {
  2. bool includeEmptyStrings = false,
  3. @Deprecated('Use includeEmptyStrings instead.') bool inclideEmptyStrings = false,
})

Splits text by occurrences of this pattern, including captured groups.

Returns a list containing the parts of text separated by matches of this pattern. If the pattern contains capturing groups, the captured text is also included in the result.

Example:

final pattern = RegExp(r'(\d+)');
final result = pattern.split('abc123def456ghi');
// Returns: ['abc', '123', 'def', '456', 'ghi']

Implementation

List<String> split(
  String text, {
  bool includeEmptyStrings = false,
  @Deprecated('Use includeEmptyStrings instead.')
  bool inclideEmptyStrings = false,
}) {
  var pattern = this;

  if (pattern is! RegExp) {
    return text.split(this);
  }

  includeEmptyStrings |= inclideEmptyStrings;

  var result = <String>[];
  var start = 0, end = 0;

  for (var match in pattern.allMatches(text)) {
    end = match.start;

    if (includeEmptyStrings || start < end) {
      result.add(text.substring(start, end));
    }

    for (var i = 1; i <= match.groupCount; i += 1) {
      result.add(match.group(i)!);
    }

    start = match.end;
  }

  if (includeEmptyStrings || start < text.length) {
    result.add(text.substring(start));
  }

  return result;
}