betweenLast method

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

Returns the content between the last occurrence of start and end.

If endOptional is true (default) and end is not found, returns content after the last start. When trim is true (default), the result is trimmed. Returns an empty string if no match is found.

Implementation

@useResult
String betweenLast(String start, String end, {bool endOptional = true, bool trim = true}) {
  if (isEmpty || start.isEmpty) {
    return '';
  }

  final int startIndex = lastIndexOf(start);
  if (startIndex == -1) {
    return '';
  }

  // An empty end can't be located: treat it as "to end of string" when optional,
  // otherwise as not-found (-1) so the guards below fall through to the no-match path.
  final int endIndex = end.isEmpty ? (endOptional ? length : -1) : lastIndexOf(end);
  final bool noEnd = endIndex == -1;
  // end must come strictly after start, and start's own delimiter must not
  // run past end (overlap), or there's no valid inner span between them.
  final bool endBeforeStart = endIndex <= startIndex;
  final bool contentOverlaps = (startIndex + start.length) > endIndex;
  if (noEnd || endBeforeStart || contentOverlaps) {
    if (endOptional) {
      final String content = substringSafe(startIndex + start.length);

      return trim ? content.trim() : content;
    }

    return '';
  }
  final String content = substringSafe(startIndex + start.length, endIndex);

  return trim ? content.trim() : content;
}