【发布时间】: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 :)