我想获取与字符串中的RegExp匹配的子字符串列表。做这个的最好方式是什么?
来自dart:core的RegExp对象具有Iterable<Match> allMatches(String input, [int start=0])方法。这是我所需要的,但我想获得字符串的Iterable,而不是匹配项。
还有method String stringMatch(String input),它返回一个String,但是只有第一个匹配项。
所以我用以下代码编写了myslef这个函数map:
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;
}
Run Code Online (Sandbox Code Playgroud)
但是在我看来,它是非常基本的功能,而且我不敢相信它不在API的任何地方。我想一定有更好的方法来完成这样的基本任务。
如果您的正则表达式仅包含一组(如new RegExp(r'(\S+)')),则可以将函数重写为:
Iterable<String> _allStringMatches(String text, RegExp regExp) =>
regExp.allMatches(text).map((m) => m.group(0));
Run Code Online (Sandbox Code Playgroud)