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

时间:2019-07-24 15:26:12

标签: flutter dart

如何在DART中实现与How to get a substring between two strings in PHP?类似的解决方案

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

4 个答案:

答案 0 :(得分:4)

您可以将String.indexOfString.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
}

答案 1 :(得分:2)

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();

答案 2 :(得分:0)

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

Array.prototype.shiftRight = function(...params) {
   
    params.forEach(item => {
        for (var i = this.length - 1; i >= 0; i--) {
            if (i === 0)
               this[0] = item
            else
               this[i] = this[i - 1];
        }
    })
}


x = [1, 2, 3];

x.shiftRight(4, 5);

console.log(x);   // [5, 4, 1]

然后将正则表达式定义为Iterable<String> _allStringMatches(String text, RegExp regExp) => regExp.allMatches(text).map((m) => m.group(0));

答案 3 :(得分:0)

我喜欢正则表达式(?<...)和前瞻(?=...)

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));
}
相关问题