Accessing named capturing groups in .NET regular expressions
Accessing a named capturing group in a .NET regular expression requires using the MatchCollection.Groups
attribute, using the capturing group name as an index. Let's fix the issues you're having in your code:
<code class="language-csharp">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());</code>
This code attempts to retrieve the value of the capturing group by accessing the Captures
collection, but it only retrieves the entire matched string. To access a specific named capturing group, you need to use the MatchCollection.Groups
attribute like this:
<code class="language-csharp">foreach (Match m in mc) { MessageBox.Show(m.Groups["link"].Value); // 将 "link" 替换为任何其他命名捕获组名称 }</code>
By using the capturing group name (for example, "link") as the index of the MatchCollection.Groups
attribute, you can retrieve the value of that specific named capturing group. In this example, the m.Groups["link"].Value
expression retrieves the value of the capturing group named "link".
The above is the detailed content of How Do I Access Named Capturing Groups in .NET Regex?. For more information, please follow other related articles on the PHP Chinese website!