split method

List<String> split(
  1. String text
)

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) {
  var result = <String>[];
  var start = 0, end = 0;

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

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

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

    start = match.end;
  }

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

  return result;
}