【问题标题】:Parse html meta keywords using regex使用正则表达式解析 html 元关键字
【发布时间】:2013-05-20 06:12:35
【问题描述】:

我需要使用正则表达式解析 html 元关键字。源字符串始终采用相同的格式,例如:

<meta name="description" content="description text">
<meta name="keywords" content="Keyword1, Keyword2, Keyword3...">
<link rel="alternate" type="application/xml+rss" href="http://example.com/rss">

我不会将 Keyword1、Keyword2 和 Keyword3 作为 List

【问题讨论】:

  • 不要使用正则表达式。使用像 HTMLAgilityPack 这样的 HTMLParser。

标签: c# html regex parsing dom


【解决方案1】:

Regex 不是解析 HTML 文件的好选择..

HTML 并不严格,其格式也不规则..

使用htmlagilitypack

您可以使用此代码通过HtmlAgilityPack检索所有关键字

HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load("http://yourWebSite.com");

List<String> keyLst= doc.DocumentNode
                        .SelectSingleNode("//meta[@name='keywords']")
                        .Attributes["content"].Value
                        .Split(',').ToList();

keyLst 现在包含所有关键字

【讨论】:

    【解决方案2】:

    说明

    如果您正在寻找一个简单的正则表达式解决方案并且您的输入并不复杂,那么您可以试试这个

    &lt;meta\b[^&gt;]*\bname=["]keywords["][^&gt;]*\bcontent=(['"]?)((?:[^,&gt;"'],?){1,})\1[&gt;] 将拉取内容字段中的值。

    第 1 组是打开的报价,然后需要在值的末尾关闭。 第 2 组是可以用逗号分割的内容。

    免责声明

    这个表达式在一些简单的边缘情况下可能会失败,这就是为什么不应该使用正则表达式来解析 HTML,而应该使用 html 解析引擎。

    C# 示例

    using System;
    using System.Text.RegularExpressions;
    namespace myapp
    {
      class Class1
        {
          static void Main(string[] args)
            {
              String sourcestring = "source string to match with pattern";
              Regex re = new Regex(@"<meta\b[^>]*\bname=[""]keywords[""][^>]*\bcontent=(['""]?)((?:[^,>""'],?){1,})\1[>]",RegexOptions.IgnoreCase);
              MatchCollection mc = re.Matches(sourcestring);
              int mIdx=0;
              foreach (Match m in mc)
               {
                for (int gIdx = 0; gIdx < m.Groups.Count; gIdx++)
                  {
                    Console.WriteLine("[{0}][{1}] = {2}", mIdx, re.GetGroupNames()[gIdx], m.Groups[gIdx].Value);
                  }
                mIdx++;
              }
            }
        }
    }
    
    $matches Array:
    (
        [0] => Array
            (
                [0] => <meta name="keywords" content="Keyword1, Keyword2, Keyword3...">
            )
    
        [1] => Array
            (
                [0] => "
            )
    
        [2] => Array
            (
                [0] => Keyword1, Keyword2, Keyword3...
            )
    
    )
    

    【讨论】:

      【解决方案3】:

      我希望我可以发表评论而不是将其作为答案提交,但我的代表太低了:(

      我理解有时需要执行正则表达式,但正如其他人所建议的那样,最好使用标准的 XML 或 HTML 解析器。它在包含意外输入变化方面更安全,甚至可以更快。

      见:https://stackoverflow.com/a/701177/1002098

      【讨论】:

        猜你喜欢
        • 2014-06-08
        • 2014-05-16
        • 1970-01-01
        • 2014-06-26
        • 2016-05-01
        • 1970-01-01
        • 2021-07-20
        相关资源
        最近更新 更多