从字符串中提取URL

时间:2012-07-28 21:58:48

标签: c# regex string extract

假设我的字符串是

http://www.test.com\r\nhttp://www.hello.com<some text here>http://www.world.com

我想提取字符串中的所有网址。输出应如下:

http://www.test.com
http://www.hello.com
http://www.world.com

我怎样才能做到这一点?

字符串中没有html标记,因此使用HTMLAgilityPack提取它们不是一个可行的选择。

3 个答案:

答案 0 :(得分:3)

在其他答案和评论中,我实际可以实施的最简单的方法是拆分方式。你知道这里有很多盲目猜测,并且最好的选择之一就是:

using System.Text.RegularExpressions;

public static List<string> ParseUrls(string input) {
    List<string> urls = new List<string>();
    const string pattern = "http://"; //here you may use a better expression to include ftp and so on
    string[] m = Regex.Split(input, pattern);
    for (int i = 0; i < m.Length; i++)
        if (i % 2 == 0){
            Match urlMatch = Regex.Match(m[i],"^(?<url>[a-zA-Z0-9/?=&.]+)", RegexOptions.Singleline);
            if(urlMatch.Success)
                urls.Add(string.Format("http://{0}", urlMatch.Groups["url"].Value)); //modify the prefix according to the chosen pattern                            
        }
    return urls;
}

答案 1 :(得分:0)

自&#34;:&#34;不是URL中的有效字符,可以假设当您搜索&#34; http://&#34;您将获得一个良好,有效的URL开头。

搜索并找到你的开始。

您可以构建一个您可能遇到的已知良好TLD列表(这将有所帮助:http://en.wikipedia.org/wiki/List_of_Internet_top-level_domains

你知道这将是你的终点;所以你可以从字符串的开头搜索这些内容。

从头开始,从此索引开始。跳过它后面的一切,它没有用。

我假设你没有子目录;因为你没有列出任何一个。

答案 2 :(得分:0)

您可以使用this question中的字符串拆分逻辑,通过“http://”搜索和拆分/。如果确实需要“http://”部分,您可以随时添加它。

编辑:请注意,您必须在每个URL的末尾搜索并过滤(例如?)\ r \ n,但这应该不是一个大问题......