如何将所有正则表达式匹配项放入字符串列表中 [英] How to put all regex matches into a string list
问题描述
我有一个随机日期列表,格式如下:
I have a list of random dates formatted like:
String x ="Text("key:[2020-08-23 22:22, 2020-08-22 10:11, 2020-02-22 12:14]"),"
我可以使用 d{4}-d{2}-d{2}sd{2}:d{2}
正则表达式来匹配所有x
中的日期:
I can use the d{4}-d{2}-d{2}sd{2}:d{2}
regex to match all dates in x
:
RegExp regExp79 = new RegExp(
r'd{4}-d{2}-d{2}sd{2}:d{2}',
);
var match79 = regExp79.allMatches("$x");
var mylistdate = match79;
所以,匹配是:
match 1 = 2020-08-22 22:22
match 2 = 2020-08-22 10:11
match 3 = 2020-02-22 12:14
我想将 Iterable
转换成一个字符串列表,这样我的列表的输出看起来像:
I want to convert the Iterable<RegExpMatch>
into a list of strings, so that the output of my list looks like:
[2020-08-22 22:22, 2020-08-22 10:11, 2020-02-22 12:14]
推荐答案
allMatches
方法 返回一个 Iterable
值.它包含所有 RegExpMatch
包含有关匹配的一些详细信息的对象.您需要在每个 RegExpMatch
对象上调用 .group(0)
方法来获取匹配的字符串值.
The allMatches
method returns an Iterable<RegExpMatch>
value. It contains all the RegExpMatch
objects that contain some details about the matches. You need to invoke the .group(0)
method on each RegExpMatch
object to get the string value of the match.
所以,你需要.map
结果:
your_regex.allMatches(x).map((z) => z.group(0)).toList()
代码:
String x ="Text("key:[2020-08-23 22:22, 2020-08-22 10:11, 2020-02-22 12:14]"),";
RegExp regExp79 = new RegExp(r'd{4}-d{2}-d{2}sd{2}:d{2}');
var mylistdate = regExp79.allMatches(x).map((z) => z.group(0)).toList();
print(mylistdate);
输出:
[2020-08-23 22:22, 2020-08-22 10:11, 2020-02-22 12:14]
这篇关于如何将所有正则表达式匹配项放入字符串列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!