如何访问 .NET Regex 中的命名捕获组? [英] How do I access named capturing groups in a .NET Regex?

查看:16
本文介绍了如何访问 .NET Regex 中的命名捕获组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难找到解释如何在 C# 中使用命名捕获组的好资源.这是我到目前为止的代码:

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?

推荐答案

使用 Match 对象的组集合,使用捕获组名称对其进行索引,例如

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);
}

这篇关于如何访问 .NET Regex 中的命名捕获组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆