'How to get substring between two strings in DART?
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
and over
I want the data
inside these two Strings and expecting result:brown fox jumps
Solution 1:[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:[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:[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();
Solution 4:[4]
You can do that with the help of regex. Create a function that will return the regex matches as
Iterable<String> _allStringMatches(String text, RegExp regExp) =>
regExp.allMatches(text).map((m) => m.group(0));
And then define your regex as RegExp(r"[quick ]{1}.*[ over]{1}"))
Solution 5:[5]
The substring functionality isn't that great, and will throw errors for strings above the "end" value.
To make it simpler user this custom function that doesn't thrown an error, instead using the max length.
String substring(String original, {required int start, int? end}) {
if (end == null) {
return original.substring(start);
}
if (original.length < end) {
return original.substring(start, original.length);
}
return original.substring(start, end);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dominik Palo |
Solution 2 | |
Solution 3 | CopsOnRoad |
Solution 4 | bimsina |
Solution 5 | Oliver Dixon |