0
Regex r = new System.Text.RegularExpressions.Regex("(\\d+)(\\w)");
Match m = r.Match("    123x   ");

MessageBox.Show(m.Captures.Count.ToString());
MessageBox.Show(m.Captures[0].Value);
MessageBox.Show(m.Captures[1].Value);

this gives me exception when run

Barmar
  • 741,623
  • 53
  • 500
  • 612
user366866
  • 55
  • 1
  • 4
  • 1
    I don't really know .NET, but I think you're supposed to use `.Groups`, not `.Captures`. See https://stackoverflow.com/questions/3320823/whats-the-difference-between-groups-and-captures-in-net-regular-expression – Barmar Nov 23 '17 at 03:27
  • it's because `m.Captures[1].Value` is **NULL**. hence you got `System.ArgumentOutOfRangeException` error. What are your expected result? – KX.T Nov 23 '17 at 04:40
  • Beacause `m.Captures` has Count of `1`, hence `m.Catures[1]` giving `System.ArgumentOutOfRangeException` – MUT Nov 23 '17 at 06:52

2 Answers2

2

Match.Captures is really Group.Captures, since Match inherits from Group, so it refers to the captures of the global group (group 0).

This can be seen in the source of the constructor of Match, where it calls the base constructor with index 0.

internal Match(Regex regex, int capcount, String text, int begpos, int len, int startpos)
  : base(text, new int[2], 0, "0") {
    ...
}

What you want is Match.Groups, or more specifically m.Groups[1].Value and m.Groups[2].Value.

Markus Jarderot
  • 86,735
  • 21
  • 136
  • 138
0
string pattern = @"(\d+)(\w)";
string input = "123x 45w 63 94b";
MatchCollection matches = Regex.Matches(input, pattern);
Console.WriteLine(matches.Count);
Console.WriteLine(matches[0].Value);
Console.WriteLine(matches[1].Value);

This the way to check for multiple please post your expected result

Thomas Rollet
  • 1,573
  • 4
  • 19
  • 33