为什么我没有获得所有正则表达式捕获?

Jez*_*Jez 5 .net c# regex

我正在使用.NET Regex来从字符串中捕获信息.我有一个用条形字符括起来的数字模式,我想挑出数字.这是我的代码:

string testStr = "|12||13||14|";
var testMatch = Regex.Match(testStr, @"^(?:\|([0-9]+)\|)+$");
Run Code Online (Sandbox Code Playgroud)

但是,testMatch.Captures只有1个条目,它等于整个字符串.为什么它不具备3项,12,13,和14?我错过了什么?

Nul*_*ion 5

您想CapturesGroup自身上使用该属性- 在这种情况下testMatch.Groups[1].这是必需的,因为正则表达式中可能有多个捕获组,并且它无法知道您指的是哪一个.

testMatch.Captures有效地使用给出testMatch.Groups[0].Captures.

对我有用:

string testStr = "|12||13||14|";
var testMatch = Regex.Match(testStr, @"^(?:\|([0-9]+)\|)+$");

int captureCtr = 0;
foreach (Capture capture in testMatch.Groups[1].Captures) 
{
    Console.WriteLine("Capture {0}: {1}", captureCtr++, capture.Value);
}
Run Code Online (Sandbox Code Playgroud)

参考: Group.Captures