如何在.NET Regex中访问命名捕获组?

如何在.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>

我已经尝试过我在各种网站上找到的其他几种“方法”,但我一直得到相同的结果。

如何访问我的正则表达式中指定的命名捕获组?


犯罪嫌疑人X
浏览 647回答 3
3回答

慕田峪4524236

您可以通过将命名捕获组字符串传递给Groups结果Match对象的属性的索引器来指定它。这是一个小例子:using&nbsp;System;using&nbsp;System.Text.RegularExpressions;class&nbsp;Program{ &nbsp;&nbsp;&nbsp;&nbsp;static&nbsp;void&nbsp;Main() &nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;String&nbsp;sample&nbsp;=&nbsp;"hello-world-"; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Regex&nbsp;regex&nbsp;=&nbsp;new&nbsp;Regex("-(?<test>[^-]*)-"); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Match&nbsp;match&nbsp;=&nbsp;regex.Match(sample); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;(match.Success) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Console.WriteLine(match.Groups["test"].Value); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP