How do I access named capturing groups in a .NET Regex?

UnkwnTech picture UnkwnTech · May 25, 2009 · Viewed 202.1k times · Source

I'm having a hard time finding a good resource that explains how to use Named Capturing Groups in C#. This is the code that I have so far:

string page = Encoding.ASCII.GetString(bytePage);
Regex qariRegex = new Regex("<td><a href=\"(?<link>.*?)\">(?<name>.*?)</a></td>");
MatchCollection mc = qariRegex.Matches(page);
CaptureCollection cc = mc[0].Captures;
MessageBox.Show(cc[0].ToString());

However this always just shows the full line:

<td><a href="/path/to/file">Name of File</a></td> 

I have experimented with several other "methods" that I've found on various websites but I keep getting the same result.

How can I access the named capturing groups that are specified in my regex?

Answer

Paolo Tedesco picture Paolo Tedesco · May 25, 2009

Use the group collection of the Match object, indexing it with the capturing group name, e.g.

foreach (Match m in mc){
    MessageBox.Show(m.Groups["link"].Value);
}