Home > Backend Development > C++ > How Do I Access Named Capturing Groups in .NET Regex?

How Do I Access Named Capturing Groups in .NET Regex?

Barbara Streisand
Release: 2025-01-12 09:10:41
Original
114 people have browsed it

How Do I Access Named Capturing Groups in .NET Regex?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template