正则表达式重复组

mat*_*thk 4 c# regex

捕获重复组总是返回最后一个元素,但这不是很有用.例如:

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

我想有一个匹配元素的集合,而不是最后一个匹配项.那可能吗?

Ani*_*dha 6

CaptureCollection

您可以使用CaptureCollection它表示captures由单个捕获组创建的集合.

如果a quantifier未应用于捕获组,则CaptureCollection包含一个Capture对象,该对象表示与Group对象相同的捕获子字符串.

如果a quantifier应用于捕获组,CaptureCollection则为每个捕获的子字符串包含一个Capture对象,该Group对象仅提供有关最后捕获的子字符串的信息.

所以你可以做到这一点

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
Run Code Online (Sandbox Code Playgroud)