betweenResult method
Extracts content between start and end delimiters.
Returns a tuple of (content between delimiters, remaining string after the closing delimiter). The second element is an empty string if nothing follows the closing delimiter.
Design: uses indexOf for start (first occurrence) and
lastIndexOf for end (last occurrence). This intentionally returns
the outermost match, so nested delimiters are included in the
content: '(a(test)b)'.betweenResult('(',')') → ('a(test)b', '').
If you need the first balanced pair instead, use between() which
uses indexOf for both delimiters.
Implementation
(String, String?)? 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 : (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 (finalFound, finalRemaining.isEmpty ? '' : finalRemaining);
}