繁体   English   中英

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

[英]Regex Groups doesn't return expected values

我在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"];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM