C#中的正则expression式组
我已经inheritance了一个包含下面的正则expression式的代码块,我试图了解它是如何得到它的结果。
var pattern = @"\[(.*?)\]"; var matches = Regex.Matches(user, pattern); if (matches.Count > 0 && matches[0].Groups.Count > 1) ...
对于inputuser == "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?
从我所了解的“集团”系列中可以看出整个比赛以及之前的比赛。 但是,上面的正则expression式不仅仅匹配[方括号] [文本] [方括号],那么为什么“jsmith”匹配呢?
另外,总是这样的情况下,这个组合集合将会存储两组:整个比赛和最后一场比赛?
( )充当捕获组。 因此,匹配数组包含C#在string中find的所有匹配项,并且子数组具有这些匹配项内的捕获组值。 如果你不希望额外的级别的捕获jut删除( ) 。
-
match.Groups[0]总是和match.Value相同,也就是整个匹配。 -
match.Groups[1]是正则expression式中的第一个捕获组。
考虑这个例子:
var pattern = @"\[(.*?)\](.*)"; var match = Regex.Match("ignored [john] John Johnson", pattern);
在这种情况下,
-
match.Value是"[john] John Johnson" -
match.Groups[0]总是和match.Value,"[john] John Johnson"。 -
match.Groups[1]是来自(.*?)的捕获组。 -
match.Groups[2]是来自(.*)的捕获组。 -
match.Groups[1].Captures是另一个维度。
考虑另一个例子:
var pattern = @"(\[.*?\])+"; var match = Regex.Match("[john][johnny]", pattern);
请注意,我们正在查找一个或多个方括号内的名字。 您需要能够分别获取每个名称。 inputCaptures !
-
match.Groups[0]总是与match.Value"[john][johnny]"。 -
match.Groups[1]是来自(\[.*?\])+的捕获组。 在这种情况下match.Value相同。 -
match.Groups[1].Captures[0]与match.Groups[1].Value -
match.Groups[1].Captures[1]是[john] -
match.Groups[1].Captures[2]是[johnny]
圆括号也标识一个组,所以匹配1是整个匹配,匹配2是方括号之间的内容。
怎么样? 答案就在这里
(.*?)
这是@“[(。*?)]的一个子组。
组[0] – 是你的整个inputstring组[1]是你的组被括号(.*?)捕获,你可以configuration正则expression式来捕获显式组(只有当你创build一个正则expression式时),或者使用(?:.*?)创build非捕获组。