关于Flutter:如何在DART中获取两个字符串之间的子字符串?

How to get substring between two strings in DART?

我如何实现类似的解决方案:如何在PHP中的两个字符串之间获取子字符串?但在DART

例如,我有一个字符串:
String data ="the quick brown fox jumps over the lazy dog"
我还有另外两个字符串:quickover
我希望在这两个字符串中包含data并期待结果:
brown fox jumps


您可以将String.indexOfString.substring结合使用:

1
2
3
4
5
6
7
8
9
10
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
}

还请注意,startIndex是包含的,而endIndex是排除的。


我喜欢正则表达式,其lookbehind (?<...)和lookahead (?=...)

1
2
3
4
5
6
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));
}


1
2
3
4
5
6
7
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();

您可以在正则表达式的帮助下进行操作。
创建一个将正则表达式匹配项返回为

的函数

1
2
Iterable<String> _allStringMatches(String text, RegExp regExp) =>
regExp.allMatches(text).map((m) => m.group(0));

然后将您的正则表达式定义为RegExp(r"[quick ]{1}.*[ over]{1}"))