Regular Expression Groups in C#

  • match.Groups[0] is always the same as match.Value, which is the entire match.
  • match.Groups[1] is the first capturing group in your regular expression.

Consider this example:

var pattern = @"\[(.*?)\](.*)";
var match = Regex.Match("ignored [john] John Johnson", pattern);

In this case,

  • match.Value is "[john] John Johnson"
  • match.Groups[0] is always the same as match.Value, "[john] John Johnson".
  • match.Groups[1] is the group of captures from the (.*?).
  • match.Groups[2] is the group of captures from the (.*).
  • match.Groups[1].Captures is yet another dimension.

Consider another example:

var pattern = @"(\[.*?\])+";
var match = Regex.Match("[john][johnny]", pattern);

Note that we are looking for one or more bracketed names in a row. You need to be able to get each name separately. Enter Captures!

  • match.Groups[0] is always the same as match.Value, "[john][johnny]".
  • match.Groups[1] is the group of captures from the (\[.*?\])+. The same as match.Value in this case.
  • match.Groups[1].Captures[0] is the same as match.Groups[1].Value
  • match.Groups[1].Captures[1] is [john]
  • match.Groups[1].Captures[2] is [johnny]

The ( ) acts as a capture group. So the matches array has all of matches that C# finds in your string and the sub array has the values of the capture groups inside of those matches. If you didn't want that extra level of capture jut remove the ( ).


Groups[0] is your entire input string.

Groups[1] is your group captured by parentheses (.*?). You can configure Regex to capture Explicit groups only (there is an option for that when you create a regex), or use (?:.*?) to create a non-capturing group.

Tags:

C#

Regex