How to put all regex matches into a string list

Viewed 1772

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]\"),"

I can use the \d{4}\-\d{2}\-\d{2}\s\d{2}:\d{2} regex to match all dates in x:

RegExp regExp79 = new RegExp(
    r'\d{4}\-\d{2}\-\d{2}\s\d{2}:\d{2}',
);
var match79 = regExp79.allMatches("$x");
var mylistdate = match79;

So, the matches are:

match 1 = 2020-08-22 22:22
match 2 = 2020-08-22 10:11
match 3 = 2020-02-22 12:14

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]
1 Answers

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.

So, you need to .map the results:

your_regex.allMatches(x).map((z) => z.group(0)).toList()

Code:

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}\s\d{2}:\d{2}');
var mylistdate = regExp79.allMatches(x).map((z) => z.group(0)).toList();
print(mylistdate);

Output:

[2020-08-23 22:22, 2020-08-22 10:11, 2020-02-22 12:14]
Related