如何将所有正则表达式匹配项放入字符串列表

编程入门 行业动态 更新时间:2024-10-27 16:30:13
本文介绍了如何将所有正则表达式匹配项放入字符串列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个随机日期列表,格式如下:

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} \s\d {2}:\d {2} 正则表达式可匹配 x :

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;

因此,匹配项为:

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

我想将 Iterable< RegExpMatch> 转换为字符串列表,以便输出我的列表如下:

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 对象,其中包含有关匹配项的一些详细信息。您需要在每个 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}\s\d{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]

更多推荐

如何将所有正则表达式匹配项放入字符串列表

本文发布于:2023-11-05 09:02:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1560424.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   如何将   放入   列表   正则表达式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!