Reputation: 844
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
Upvotes: 37
Views: 68307
Reputation: 1026
void main() {
String str = "the quick brown fox jumps over the lazy dog";
String start = "quick";
String end = "over";
print(getSringBetween(str, start, end));
//OUT PUTS: brown fox jumps
}
String getSringBetween(str, start, end) {
return str.split(start).last.split(end)[0].trim();
}
Upvotes: 1
Reputation: 101
For future researchers: To start form the beginning of a string to a specific symbol or character;
Using substring and indexOf which is faster than regExp do this:
void main() {
const str = "Cars/Horses";
final endIndex = str.indexOf("/", 0);
print(str.substring(0, endIndex)); // Cars
}
This might just help someone
Upvotes: 3
Reputation: 7405
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);
}
Upvotes: 1
Reputation: 267474
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();
Upvotes: 5
Reputation: 276997
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.
Upvotes: 79
Reputation: 20118
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));
}
Upvotes: 10
Reputation: 444
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}"))
Upvotes: 2