首页 文章

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

提问于
浏览
235

我很难找到一个很好的资源来解释如何在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>

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

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

4 回答

  • 103

    另外,如果有人在执行搜索Regex对象之前需要组名的用例,他可以使用:

    var regex = new Regex(pattern); // initialized somewhere
    // ...
    var groupNames = regex.GetGroupNames();
    
  • 1

    您可以通过将命名捕获组字符串传递给生成的 Match 对象的 Groups 属性的索引器来指定它 .

    这是一个小例子:

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

    以下代码示例将匹配模式,即使中间有空格字符 . 即:

    <td><a href='/path/to/file'>Name of File</a></td>
    

    以及:

    <td> <a      href='/path/to/file' >Name of File</a>  </td>
    

    方法返回true或false,具体取决于输入htmlTd字符串是否与模式匹配或否 . 如果匹配,则out参数分别包含链接和名称 .

    /// <summary>
    /// Assigns proper values to link and name, if the htmlId matches the pattern
    /// </summary>
    /// <returns>true if success, false otherwise</returns>
    public static bool TryGetHrefDetails(string htmlTd, out string link, out string name)
    {
        link = null;
        name = null;
    
        string pattern = "<td>\\s*<a\\s*href\\s*=\\s*(?:\"(?<link>[^\"]*)\"|(?<link>\\S+))\\s*>(?<name>.*)\\s*</a>\\s*</td>";
    
        if (Regex.IsMatch(htmlTd, pattern))
        {
            Regex r = new Regex(pattern,  RegexOptions.IgnoreCase | RegexOptions.Compiled);
            link = r.Match(htmlTd).Result("${link}");
            name = r.Match(htmlTd).Result("${name}");
            return true;
        }
        else
            return false;
    }
    

    我测试了这个,它工作正常 .

  • 11

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

    foreach (Match m in mc){
        MessageBox.Show(m.Groups["link"].Value);
    }
    

相关问题