Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么我没有得到我所有的正则表达式捕获?_C#_.net_Regex - Fatal编程技术网

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

C# 为什么我没有得到我所有的正则表达式捕获?,c#,.net,regex,C#,.net,Regex,我正在使用.NET的Regex从字符串中捕获信息。我有一个用条形字符括起来的数字模式,我想挑出这些数字。这是我的密码: string testStr = "|12||13||14|"; var testMatch = Regex.Match(testStr, @"^(?:\|([0-9]+)\|)+$"); 但是,testMatch.Captures只有一个条目,它等于整个字符串。为什么它没有3个条目,12、13和14?我缺少什么?您想在组本身上使用捕获属性-在本例中为testMatch.Gr

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

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

但是,
testMatch.Captures
只有一个条目,它等于整个字符串。为什么它没有3个条目,
12
13
14
?我缺少什么?

您想在
组本身上使用
捕获
属性-在本例中为
testMatch.Groups[1]
。这是必需的,因为regex中可能有多个捕获组,它无法知道您所指的是哪一个

使用
testMatch.Captures
有效地提供
testMatch.Groups[0]。捕获

对我来说:


推荐人:嗯。我还以为它捕获了
14
。无论如何,一个被捕获的群体通常捕获一件事;你可以用
匹配
(?这有点不真实,但我需要看看
.Groups[1]。捕获[1/2/3…]
@Jez我澄清了一下我的答案。
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);
}