How to get substring between two strings in DART?
You can use String.indexOf
combined with String.substring
:
void main() {
const str = "the quick brown fox jumps over the lazy dog";
const start = "quick";
const end = "over";
final startIndex = str.indexOf(start);
final endIndex = str.indexOf(end, startIndex + start.length);
print(str.substring(startIndex + start.length, endIndex)); // brown fox jumps
}
Note also that the startIndex
is inclusive, while the endIndex
is exclusive.
final str = 'the quick brown fox jumps over the lazy dog';
final start = 'quick';
final end = 'over';
final startIndex = str.indexOf(start);
final endIndex = str.indexOf(end);
final result = str.substring(startIndex + start.length, endIndex).trim();
I love regexp with lookbehind (?<...)
and lookahead (?=...)
:
void main() {
var re = RegExp(r'(?<=quick)(.*)(?=over)');
String data = "the quick brown fox jumps over the lazy dog";
var match = re.firstMatch(data);
if (match != null) print(match.group(0));
}