我在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"];
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句