split method

List<String> split(
  1. String text, {
  2. 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 inclideEmptyStrings = false}) {
  if (this is! RegExp) {
    return text.split(this);
  }

  var regEx = this as RegExp;
  var result = <String>[];
  var start = 0, end = 0;

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

    if (inclideEmptyStrings || 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 (inclideEmptyStrings || start < text.length) {
    result.add(text.substring(start));
  }

  return result;
}