c#正则表达式,用于在<a> with specific ending

时间:2015-06-03 20:14:50

标签: c# regex

I need a regex pattern for finding links in a string (with HTML code) to get the links with file endings like .gif or .png

Example String:

<a href="//site.com/folder/picture.png" target="_blank">picture.png</a>

For now I get everything between the " " and the text between the <a> and </a>.

I want to get this:

Href = //site.com/folder/picture.png String = picture.png

My code so far:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace downloader
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        string url = textBox1.Text;
        string s = gethtmlcode(url);
        foreach (LinkItem i in LinkFinder.Find(s))
        {
            richTextBox1.Text += Convert.ToString(i);
        }

    }


    static string gethtmlcode(string url)
    {
        using (WebClient client = new WebClient())
        {
            string htmlCode = client.DownloadString(url);
            return htmlCode;
        }
    }

    public struct LinkItem
    {
        public string Href;
        public string Text;
        public override string ToString()
        {
            return Href + "\n\t" + Text + "\n\t";
        }
    }
    static class LinkFinder
    {
        public static List<LinkItem> Find(string file)
        {
            List<LinkItem> list = new List<LinkItem>();

            // 1.
            // Find all matches in file.
            MatchCollection m1 = Regex.Matches(file, @"(<a.*?>.*?</a>)",
                RegexOptions.Singleline);

            // 2.
            // Loop over each match.
            foreach (Match m in m1)
            {
                string value = m.Groups[1].Value;
                LinkItem i = new LinkItem();

                // 3.
                // Get href attribute.
                Match m2 = Regex.Match(value, @"href=\""(.*?)\""",
                RegexOptions.Singleline);
                if (m2.Success)
                {
                    i.Href = m2.Groups[1].Value;
                }

                // 4.
                // Remove inner tags from text.
                string t = Regex.Replace(value, @"\s*<.*?>\s*", "",
                RegexOptions.Singleline);
                i.Text = t;

                list.Add(i);
            }
            return list;
        }
    }

}

}

1 个答案:

答案 0 :(得分:1)

我建议使用 HtmlAgilityPack 执行此任务。使用管理NuGet包解决方案菜单进行安装,并添加以下方法:

/// <summary>
/// Collects a href attribute values and a node values if image extension is jpg or png
/// </summary>
/// <param name="html">HTML string or an URL</param>
/// <returns>A key-value pair list of href values and a node values</returns>
private List<KeyValuePair<string, string>> GetLinksWithHtmlAgilityPack(string html)
{
    var result = new List<KeyValuePair<string, string>>();
    HtmlAgilityPack.HtmlDocument hap;
    Uri uriResult;
    if (Uri.TryCreate(html, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp)
    { // html is a URL 
        var doc = new HtmlAgilityPack.HtmlWeb();
        hap = doc.Load(uriResult.AbsoluteUri);
    }
    else
    { // html is a string
        hap = new HtmlAgilityPack.HtmlDocument();
        hap.LoadHtml(html);
    }
    var nodes = hap.DocumentNode.SelectNodes("//a");
    if (nodes != null)
        foreach (var node in nodes)
            if (Path.GetExtension(node.InnerText.Trim()).ToLower() == ".png" ||
                    Path.GetExtension(node.InnerText.Trim()).ToLower() == ".jpg")
            result.Add(new KeyValuePair<string,string>(node.GetAttributeValue("href", null), node.InnerText));
    return result;
}

然后,将其用作(我使用虚拟字符串,仅用于演示)

var result = GetLinksWithHtmlAgilityPack("<a href=\"//site.com/folder/picture.png\" target=\"_blank\">picture.png</a><a href=\"//site.com/folder/picture.bmp\" target=\"_blank\">picture.bmp</a>");

输出:

enter image description here

或者,使用URL,例如:

var result = GetLinksWithHtmlAgilityPack("http://www.google.com");