36

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

Sukhchain Singh
  • 834
  • 1
  • 8
  • 26

6 Answers6

75

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.

Dominik Palo
  • 2,873
  • 4
  • 29
  • 52
Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432
9

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));
}
Spatz
  • 18,640
  • 7
  • 62
  • 66
  • Thank you, my string was very large so [Rémi Rousselet's](https://stackoverflow.com/a/57186482/7814638) answer didn't helped. This one worked like a charm. – Sukhchain Singh Jul 24 '19 at 16:08
4
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();
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
2

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

Feshibaba
  • 89
  • 1
  • 6
1

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}"))

bimsina
  • 414
  • 5
  • 12
0

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);
}
Oliver Dixon
  • 7,012
  • 5
  • 61
  • 95