正则表达式重复组 [英] Regex repetition group

查看:672
本文介绍了正则表达式重复组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

捕获重复组总是返回的最后一个元素,但不是很有益的。例如:

Capturing a repetition group is always returning the last element but that is not quite helpfull. For example:

var regex = new RegEx("^(?<somea>a)+$");
var match = regex.Match("aaa");
match.Group["somea"]; // return "a"



我想有匹配元素的集合,而不是最后一场比赛中项目。
是可能的吗?

I would like to have a collection of match element instead of the last match item. Is that possible?

推荐答案

您可以使用 CaptureCollection 表示设定捕获的由一个单一的捕获组进行。

CaptureCollection

You can use CaptureCollection which represents the set of captures made by a single capturing group.

如果一个量词不应用于捕获组,在 CaptureCollection 包含一个捕获表示相同捕获的子字符串作为集团的对象对象。

If a quantifier is not applied to a capturing group, the CaptureCollection includes a single Capture object that represents the same captured substring as the Group object.

如果一个量词应用于捕获组,在 CaptureCollection 包括每个捕获子一个捕获对象,而对象只提供了关于在最后捕获的子字符串的信息。

If a quantifier is applied to a capturing group, the CaptureCollection includes one Capture object for each captured substring, and the Group object provides information only about the last captured substring.

所以,你可以做到这一点。

So you can do this

var regex = new Regex("^(?<somea>a)+$");
var match = regex.Match("aaa");
List<string> aCaptures=match.Groups["somea"]
                            .Captures.Cast<Capture>()
                            .Select(x=>x.Value)
                            .ToList<string>();

//aCaptures would now contain a list of a

这篇关于正则表达式重复组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆