【问题标题】:Get anchor tag HREF and VALUE获取锚标记 HREF 和 VALUE
【发布时间】:2017-05-14 01:26:15
【问题描述】:

我有一个如下所示的字符串:

<a href="http://forum.tibia.com/forum/?action=board&boardid=476">Amera</a><br><font class="ff_info">This board is for general discussions related to the game world Amera.</font>

如何忽略/删除&lt;/a&gt; 之后的所有内容,然后只获取网址:http://forum.tibia.com/forum/?action=board&amp;boardid=476 和值Amera

所以之后,我想要 2 个变量及其值,例如:

string url = "http://forum.tibia.com/forum/?action=board&amp;boardid=476";

string value = "Amera";

我试过这个来获取价值:

string value = System.Text.RegularExpressions.Regex.Replace(MYSTRING, "(<[a|A][^>]*>|)", "");

但它会返回:

Amera</a><br><font class="ff_info">This board is for general discussions related to the game world Amera.</font>

【问题讨论】:

    标签: c# regex string parsing find


    【解决方案1】:

    要获取 URL,不妨试试这个正则表达式模式:/href=\"(.*)\"/

    ...并获取 &gt; Amera &lt;/a&gt; 之间的值 使用类似的模式:&gt;(.+?)&lt;/a&gt;

    ...虽然,这似乎远非完美...

    【讨论】:

      【解决方案2】:

      如果 a 标记不包含更多属性,您可以仅将其用于 URL:

      \bhref="(.*?)"
      

      URL 和文本稍微复杂一点:

      <a\b[^>]*?\bhref="([^"]*?)"[^>]*?>(.*?)<\/a>
      

      所以在C#代码中(引号需要转义!):

      var html = "<a href=\"http://forum.tibia.com/forum/?action=board&boardid=476\">Amera</a><br><font class=\"ff_info\">This board is for general discussions related to the game world Amera.</font>";
      var match = Regex.Match(html, "<a\\b[^>]*?\\bhref=\"([^\"]*?)\"[^>]*?>(.*?)<\\/a>", RegexOptions.IgnoreCase);
      if (match.Success) {
          var url = match.Groups[1];
          var text = match.Groups[2]
      }
      

      【讨论】:

      • 网址完美运行。但是我怎样才能得到a-tags中的文本呢? (价值)
      • @rickastley 抱歉,我忘记了文本 - 使用适用于 url 和文本的新正则表达式更新了帖子。
      【解决方案3】:

      试试这个:

      HtmlDocument dc = new HtmlAgilityPack.HtmlDocument();
              dc.LoadHtml("<a href='http://forum.tibia.com/forum/?action=board&boardid=476'>Amera</a><br><font class='ff_info'>This board is for general discussions related to the game world Amera.</font>");
              foreach (HtmlNode link in dc.DocumentNode.SelectNodes("a"))
              {
                  string url = link.Attributes["href"].Value; // http://forum.tibia.com/forum/?action=board&boardid=476
                  string value = link.InnerText; // Amera
              }
      

      【讨论】:

        猜你喜欢
        • 2015-09-23
        • 1970-01-01
        • 2020-10-13
        • 1970-01-01
        • 1970-01-01
        • 2011-04-08
        • 2019-10-06
        • 2018-08-28
        • 2011-03-29
        相关资源
        最近更新 更多