Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get substring between two strings in DART?

Tags:

flutter

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

like image 905
Sukhchain Singh Avatar asked Jul 24 '19 15:07

Sukhchain Singh


2 Answers

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.

like image 113
Rémi Rousselet Avatar answered Oct 12 '22 05:10

Rémi Rousselet


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));
}
like image 45
Spatz Avatar answered Oct 12 '22 07:10

Spatz