splitBetween method

List<String> splitBetween(
  1. String start,
  2. String end
)

Implementation

List<String> splitBetween(String start, String end) {
  if (start.length != 1 || end.length != 1) {
    throw ArgumentError('Delimiter must be a single character');
  }

  final startIndex = indexOf(start);
  if (startIndex == -1) throw ArgumentError('Start delimiter not found');

  int balance = 1;
  int currentIndex = startIndex + 1;

  // find matching closing delimiter
  while (currentIndex < length && balance > 0) {
    if (this[currentIndex] == start) balance++;
    if (this[currentIndex] == end) balance--;
    currentIndex++;
  }

  if (balance != 0) throw ArgumentError('Unbalanced delimiters');

  return [
    substring(0, startIndex), // before
    substring(startIndex + 1, currentIndex - 1), // between
    substring(currentIndex) // after
  ];
}