betweenResult method

  1. @useResult
BetweenResult? betweenResult(
  1. String start,
  2. String end, {
  3. bool endOptional = false,
  4. bool trim = true,
})

Returns a BetweenResult of content between start and end delimiters plus the remaining string, or null if not found.

When endOptional is true and end is not found, returns the content after start. When trim is true (default), results are trimmed.

Uses indexOf for start (first occurrence) and lastIndexOf for end (last occurrence), returning the outermost match. Audited: 2026-06-12 11:26 EDT

Implementation

@useResult
BetweenResult? betweenResult(
  String start,
  String end, {
  bool endOptional = false,
  bool trim = true,
}) {
  if (isEmpty || start.isEmpty || end.isEmpty) {
    return null;
  }

  final int startIndex = indexOf(start);
  if (startIndex == -1) {
    return null;
  }

  // indexOf/lastIndexOf return UTF-16 code-unit offsets, so every slice in
  // this method uses code-unit substring. The grapheme-indexed substringSafe
  // used before shifted the cuts whenever an emoji or combining mark came
  // before a delimiter, returning the wrong span or dropping text.
  final int endIndex = lastIndexOf(end);
  if (endIndex == -1) {
    // If end is not found and it's optional, return the tail after start.
    if (endOptional) {
      final String content = substring(startIndex + start.length);
      final String finalContent = trim ? content.trim() : content;

      return finalContent.isEmpty ? null : BetweenResult(finalContent, null);
    }

    return null;
  }

  if (startIndex >= endIndex || (startIndex + start.length) > endIndex) {
    return null;
  }

  final String found = substring(startIndex + start.length, endIndex);

  final String remaining = substring(0, startIndex) + substring(endIndex + end.length);

  final String finalFound = trim ? found.trim() : found;

  final String finalRemaining = trim
      ? remaining.replaceAll(RegExp(r'\s+'), ' ').trim()
      : remaining;

  return BetweenResult(
    finalFound,
    finalRemaining.isEmpty ? '' : finalRemaining,
  );
}