betweenResult method
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.
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;
}
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 = substringSafe(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 = substringSafe(startIndex + start.length, endIndex);
final String remaining = substringSafe(0, startIndex) + substringSafe(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,
);
}