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 '';
  }

  final int endIndex = end.isEmpty ? (endOptional ? length : -1) : lastIndexOf(end);
  final bool noEnd = endIndex == -1;
  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;
}