【问题标题】:Best way to get all substrings matching a RegExp in Dart在 Dart 中获取与 RegExp 匹配的所有子字符串的最佳方法
【发布时间】:2014-12-18 11:05:19
【问题描述】:

我想获取与字符串中的正则表达式匹配的子字符串列表。最好的方法是什么?

来自 dart:core 的 RegExp 对象具有 Iterable<Match> allMatches(String input, [int start=0]) 方法。这正是我所需要的,但我想获得 Iterable of Strings,而不是匹配。

还有String stringMatch(String input)方法,它返回一个字符串,但只有第一个匹配项。

所以我用map写了myslef这个函数:

Iterable<String> _allStringMatches(String text, RegExp regExp) {
  Iterable<Match> matches = regExp.allMatches(text);
  List<Match> listOfMatches = matches.toList();

  // TODO: there must be a better way to get list of Strings out of list of Matches
  Iterable<String> listOfStringMatches = listOfMatches.map((Match m) {
    return m.input.substring(m.start, m.end);
  });

  return listOfStringMatches;
}

但在我看来,它是非常基本的功能,我不敢相信它不在 API 的任何地方。我想一定有更好的方法来完成这样的基本任务。

【问题讨论】:

  • 你能发布一个示例字符串以及你想要的子字符串吗?您可以遍历所有匹配项并获得group(n),n=0 表示整个匹配项,其他 n 表示部分匹配项。
  • group(0) 的匹配返回匹配的整个字符串。你可以通过使用它来简化你的代码。
  • 看我的帖子,@fog :)

标签: regex dart


【解决方案1】:

如果您的正则表达式只包含一组(如new RegExp(r'(\S+)')),您可以将您的函数重写为:

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

【讨论】:

  • 更短:regexp.allMatches(text).map((m)=&gt;m[0]).
猜你喜欢
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2015-10-03
  • 2011-02-07
  • 1970-01-01
  • 1970-01-01
  • 2012-08-15
  • 2016-04-19
相关资源
最近更新 更多