正则表达式组不返回预期值

时间:2016-01-27 00:01:23

标签: c# regex

我在Visual Studio的C#interactive中尝试了以下代码

> using System.Text.RegularExpressions;
> var re = new Regex(@"(\d\d/\d\d?\/\d\d\d\d)");
> var r = re.Match("01/01/2016 02/02/2016").Groups;
> r
GroupCollection(2) { [01/01/2016], [01/01/2016] }

为什么它不会返回预期的[01/01/2016], [02/02/2016]

1 个答案:

答案 0 :(得分:2)

似乎包含第一次匹配两次,因为Groups[0]包含整个匹配字符串,而您定义的实际捕获组不会在Groups[1]之前启动。

您会看到多个捕获组更清晰:

> var re = new Regex(@"(\d)-([A-Z])");
> var r = re.Match("5-D").Groups;

> r[0]
{5-D}
    [System.Text.RegularExpressions.Match]: {5-D}
    base {System.Text.RegularExpressions.Capture}: {5-D}
    Captures: {System.Text.RegularExpressions.CaptureCollection}
    Success: true
> r[1]
{5}
    base {System.Text.RegularExpressions.Capture}: {5}
    Captures: {System.Text.RegularExpressions.CaptureCollection}
    Success: true
> r[2]
{D}
    base {System.Text.RegularExpressions.Capture}: {D}
    Captures: {System.Text.RegularExpressions.CaptureCollection}
    Success: true

但是你想要做的是使用Regex.Matches

  

在指定的输入字符串中搜索所有正则表达式。

使用组名

为避免基于0的索引混淆和其他混淆,命名组很有用:

var re = new Regex(@"(?<date>\d\d/\d\d?\/\d\d\d\d)");
var dateGroup = re.Match("01/01/2016").Groups["date"];
相关问题