【发布时间】:2011-09-16 13:56:00
【问题描述】:
我继承了一个包含以下正则表达式的代码块,我正在尝试了解它是如何获得结果的。
var pattern = @"\[(.*?)\]";
var matches = Regex.Matches(user, pattern);
if (matches.Count > 0 && matches[0].Groups.Count > 1)
...
对于输入user == "Josh Smith [jsmith]":
matches.Count == 1
matches[0].Value == "[jsmith]"
...我理解。但后来:
matches[0].Groups.Count == 2
matches[0].Groups[0].Value == "[jsmith]"
matches[0].Groups[1].Value == "jsmith" <=== how?
根据我的理解查看this question,Groups 集合存储了整个比赛以及上一场比赛。但是,上面的正则表达式不是只匹配 [open square bracket] [text] [close square bracket] 那么为什么“jsmith”会匹配?
另外,groups 集合是否总是恰好存储 2 个组:整个匹配和最后一个匹配?
【问题讨论】: