如何在.NET Regex中訪問命名捕獲組?我很難找到一個(gè)很好的資源來解釋如何在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>我已經(jīng)嘗試過我在各種網(wǎng)站上找到的其他幾種“方法”,但我一直得到相同的結(jié)果。如何訪問我的正則表達(dá)式中指定的命名捕獲組?
3 回答

慕田峪4524236
TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以通過將命名捕獲組字符串傳遞給Groups
結(jié)果Match
對(duì)象的屬性的索引器來指定它。
這是一個(gè)小例子:
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 關(guān)注
- 708 瀏覽
添加回答
舉報(bào)
0/150
提交
取消