[英]Extracting URL from string
假設我的字符串是
http://www.test.com\r\nhttp://www.hello.com<some text here>http://www.world.com
我想提取字符串中的所有URL。 輸出應如下所示:
http://www.test.com
http://www.hello.com
http://www.world.com
我該如何實現?
字符串中沒有html標記,因此使用HTMLAgilityPack提取它們不是可行的選擇。
在其他答案和評論中,我實際上可以實現的最簡單方法是拆分方法。 您知道這里有很多盲目的猜測,而最好的選擇之一可能是:
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;
}
由於“:”不是URL中的有效字符,因此可以假定當您搜索“ http://”時,將為您提供一個有效的URL開頭。
搜索此並找到您的起點。
您可以構建可能遇到的已知良好TLD的列表(這將有所幫助: http : //en.wikipedia.org/wiki/List_of_Internet_top-level_domains )
您知道這將是您的終點; 因此您可以從字符串開頭搜索這些內容。
從頭開始,然后從該索引開始。 跳過所有內容,這是不好的。
我假設您沒有子目錄; 因為您沒有列出任何一個。
您可以通過搜索和拆分“ http://”來使用此問題中的字符串拆分邏輯。 如果確實需要“ http://”部分,則以后可以隨時添加。
編輯: 請注意,之后您必須在每個URL的末尾搜索和過濾(諸如?)\\ r \\ n,但這應該不是一個大問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.