How to get substring between two strings in DART?
36,764
Solution 1
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.
Solution 2
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));
}
Solution 3
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();
Related videos on Youtube
Author by
Sukhchain Singh
Updated on July 09, 2022Comments
-
Sukhchain Singh almost 2 years
How can i achieve similar solution to: How to get a substring between two strings in PHP? but in DART
For example I have a String:
String data = "the quick brown fox jumps over the lazy dog"
I have two other Strings:quick
andover
I want thedata
inside these two Strings and expecting result:
brown fox jumps
-
Ajil O. over 4 yearsI was almost about to post an answer with
RegExp
. But this one's better -
Sukhchain Singh over 4 yearsThank you, my string was very large so Rémi Rousselet's answer didn't helped. This one worked like a charm.
-
Sukhchain Singh over 4 yearsMy String is actually unformatted
HTML
and is very long.substring
method failed with RangeError. So, @Sergey Solodukhin's answer worked for me. This one is awesome for smaller Strings. Thank you. -
Rémi Rousselet over 4 years@SukhchainSingh it was a bug. I've just fixed it
-
Sukhchain Singh over 4 years@RémiRousselet Thank you, it worked. It's lot faster than regexp as expected :)
-
Spatz over 4 yearsWhat's about real data? Word order may change "the over quick brown fox jumps the lazy dog" or one keyword may be absent.
-
Sukhchain Singh over 4 years@SergeySolodukhin No it's not absent in my case and order will be not changed too.