如何在.NET Regex中访问命名捕获组?我很难找到一个很好的资源来解释如何在C#中使用命名捕获组。这是我到目前为止的代码: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());然而,这总是只显示整行:<td><a href="/path/to/file">Name of File</a></td>我已经尝试过我在各种网站上找到的其他几种“方法”,但我一直得到相同的结果。如何访问我的正则表达式中指定的命名捕获组?
3 回答
慕田峪4524236
TA贡献1875条经验 获得超5个赞
您可以通过将命名捕获组字符串传递给Groups结果Match对象的属性的索引器来指定它。
这是一个小例子:
using System;using System.Text.RegularExpressions;class Program{
static void Main()
{
String sample = "hello-world-";
Regex regex = new Regex("-(?<test>[^-]*)-");
Match match = regex.Match(sample);
if (match.Success)
{
Console.WriteLine(match.Groups["test"].Value);
}
}}- 3 回答
- 0 关注
- 738 浏览
添加回答
举报
0/150
提交
取消
