Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.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#_Regex - Fatal编程技术网

C# 对正则表达式中多个匹配项的混淆

C# 对正则表达式中多个匹配项的混淆,c#,regex,C#,Regex,我已经在一个正则表达式测试仪中测试了我的正则表达式,语句本身似乎应该可以工作,但是它没有像应该的那样匹配4个对象,而是只匹配1个(整个字符串),我不确定为什么它会这样做 rgx = new Regex(@"^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$"); matches = rgx.Matches("0.0.0.95"); 在这一点上,如果我这样做: foreach (Match m in matches) { Console.WriteLine(

我已经在一个正则表达式测试仪中测试了我的正则表达式,语句本身似乎应该可以工作,但是它没有像应该的那样匹配4个对象,而是只匹配1个(整个字符串),我不确定为什么它会这样做

rgx = new Regex(@"^([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)$");
matches = rgx.Matches("0.0.0.95");
在这一点上,如果我这样做:

foreach (Match m in matches)
{
    Console.WriteLine(m.Value);
}
当它应该匹配0、0、0和95而不是整个字符串时,它将只显示“0.0.0.95”。我做错了什么

答案-整个字符串的单个匹配项包含我正在查找的组匹配项,以以下方式访问:

r.r1 = Convert.ToInt32(m.Groups[1].Value);
r.r2 = Convert.ToInt32(m.Groups[2].Value);
r.r3 = Convert.ToInt32(m.Groups[3].Value);
r.r4 = Convert.ToInt32(m.Groups[4].Value);

在这种情况下,您不会得到多个匹配项-其中只有一个匹配项,但它有四个捕获组:

有一个特殊的组号0,它包含整个匹配

因此,您需要如下修改您的程序:

Console.WriteLine("One:'{0}' Two:'{1}' Three:'{2}' Four:'{3}'"
,   m.Groups[1].Value
,   m.Groups[2].Value
,   m.Groups[3].Value
,   m.Groups[4].Value
);

在MSDN中搜索关于组匹配的信息。感谢trickI编辑了您的标题。请参阅“”,其中的共识是“不,他们不应该”。
Console.WriteLine("One:'{0}' Two:'{1}' Three:'{2}' Four:'{3}'"
,   m.Groups[1].Value
,   m.Groups[2].Value
,   m.Groups[3].Value
,   m.Groups[4].Value
);