C#中的正则表达式组

时间:2011-06-16 17:12:03

标签: c# regex

我继承了一个包含以下正则表达式的代码块,我试图了解它是如何获得结果的。

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群组集合存储整个匹配以及上一个匹配。但是,上面的正则表达式是否只与[空方括号] [文本] [关闭方括号]匹配,为什么“jsmith”会匹配?

此外,群组集合总是会存储两组:整场比赛和最后一场比赛吗?

5 个答案:

答案 0 :(得分:90)

  • match.Groups[0]始终与match.Value相同,即整个匹配。
  • match.Groups[1]是正则表达式中的第一个捕获组。

考虑这个例子:

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);

请注意,我们正在寻找连续的一个或多个括号内的名称。您需要能够单独获取每个名称。输入Captures

  • 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 :(得分:22)

( )充当捕获组。因此,matches数组具有C#在字符串中找到的所有匹配项,子数组具有这些匹配项中捕获组的值。如果您不希望获得额外级别的捕获,请移除( )

答案 2 :(得分:2)

括号也在识别一个组,因此匹配1是整个匹配,匹配2是方括号之间找到的内容。

答案 3 :(得分:2)

如何?答案就在这里

(.*?)

这是@“[(。*?)];

的子组

答案 4 :(得分:1)

Groups[0]是您的整个输入字符串。

Groups[1]是由括号(.*?)捕获的群组。您可以将Regex配置为仅捕获显式组(创建正则表达式时有一个选项),或使用(?:.*?)创建非捕获组。