【问题标题】:Get "Title" attribute from html link using Regex使用正则表达式从 html 链接获取“标题”属性
【发布时间】:2009-05-12 15:32:49
【问题描述】:

我有以下正则表达式来匹配从我们的自定义 cms 生成的页面上的所有链接标签

<a\s+((?:(?:\w+\s*=\s*)(?:\w+|"[^"]*"|'[^']*'))*?\s*href\s*=\s*(?<url>\w+|"[^"]*"|'[^']*')(?:(?:\s+\w+\s*=\s*)(?:\w+|"[^"]*"|'[^']*'))*?)>.+?</a>

我们正在使用 c# 循环遍历所有匹配项,并在呈现页面内容之前为每个链接(用于跟踪软件)添加一个 onclick 事件。 我需要解析链接并向 onclick 函数添加一个参数,即“链接名称”。

我打算修改正则表达式以获得以下子组

  • 链接的标题属性
  • 如果链接包含图像标签,请获取 图片的替代文字
  • 链接的文字

然后我可以检查每个子组的匹配以获取链接的相关名称。

我将如何修改上述正则表达式来做到这一点,或者我可以使用 c# 代码实现相同的想法吗?

【问题讨论】:

  • 您正在使用 ASP.NET 生成此页面?
  • 能否请一些好心的模组在某个时候将此添加到常见问题解答中?
  • 是的,我正在使用 ASP.NET 生成页面

标签: c# .net html regex


【解决方案1】:

正则表达式根本不擅长解析 HTML(请参阅 Can you provide some examples of why it is hard to parse XML and HTML with a regex? 了解原因)。您需要的是一个 HTML 解析器。有关使用各种解析器的示例,请参阅 Can you provide an example of parsing HTML with your favorite parser?

您可能对HTMLAgilityPack answer特别感兴趣。

【讨论】:

  • 是的,我可以看到正则表达式在解析 html 方面并不是特别出色,我为什么(以及我缺乏正则表达式知识)正在为此苦苦挣扎。请记住,我不能保证这个应用程序有 xhtml,你能推荐一个好的 c# 解析器来实现上述目标吗?
  • 抱歉错过了 HTMLAgilityPack 的锚点,请看一下,谢谢
【解决方案2】:

试试这个:

Regex reg = new Regex("<a[^>]*?title=\"([^\"]*?\"[^>]*?>");

几个问题:

  • 这将匹配区分大小写,您可能需要调整它
  • 这需要title属性既存在又被引用
    • 当然,如果 title 属性不存在,你可能不想要匹配?

要提取,请使用组集合:

reg.Match("<a href=\"#\" title=\"Hello\">Howdy</a>").Groups[1].Value

【讨论】:

  • 不幸的是,如果没有标题标签,我确实想匹配此特定 cms 中的内容质量非常差的 html,所以如果标题不存在,我需要检查图像 alt 然后链接文本。跨度>
【解决方案3】:

感谢混沌。 Owens 向我介绍了 HtmlAgilityPack 库,它很棒。最后我用它来解决我的问题,如下所示。 我会毫不犹豫地向其他人推荐这个库。

   HtmlDocument htmldoc = new HtmlDocument();
    htmldoc.LoadHtml(content);
    HtmlNodeCollection linkNodes = htmldoc.DocumentNode.SelectNodes("//a[@href]");
    if (linkNodes != null)
    {
        foreach (HtmlNode linkNode in linkNodes)
        {
            string linkTitle = linkNode.GetAttributeValue("title", string.Empty);
            //If no title attribute exists check for an image alt tag
            if (linkTitle == string.Empty)
            {
                HtmlNode imageNode = linkNode.SelectSingleNode("img[@alt]");
                if (imageNode != null)
                {
                    linkTitle = imageNode.GetAttributeValue("alt", string.Empty);
                }
            }
            //If no image alt tag check for span with text
            if (linkTitle == string.Empty)
            {
                HtmlNode spanNode = linkNode.SelectSingleNode("span");
                if (spanNode != null)
                {
                    linkTitle = spanNode.InnerText;
                }
            }

            if (linkTitle == string.Empty)
            {
                if (!linkNode.HasChildNodes)
                {
                    linkTitle = linkNode.InnerText;
                }
            }

        }
    }

【讨论】:

  • 我喜欢这个,虽然我不认为这是有意的:“我会坚决向其他人推荐这个库。”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-01
  • 2013-09-05
  • 2016-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多