betweenLast method

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

Extracts content between last occurrence of start and end.

If endOptional is true and end is not found, returns content after last start.

Implementation

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);
  if (endIndex == -1 || endIndex <= startIndex || (startIndex + start.length) > endIndex) {
    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;
}