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

本文关键字:返回 正则表达式 | 更新日期: 2023-09-27 18:31:57

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

> 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]

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

它似乎包含两次第一个匹配项,因为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"];