2012-02-03 47 views
8

可能重复:
regex for URL including query string从文本获取URL

我有一个文本或消息。

嘿!试试这个http://www.test.com/test.aspx?id=53

我们的要求是获得来自text.We链接使用下面的代码

List<string> list = new List<string>(); 
Regex urlRx = new 
Regex(@"(?<url>(http:|https:[/][/]|www.)([a-z]|[A-Z]|[0-9]|[/.]|[~])*)", 
RegexOptions.IgnoreCase); 

MatchCollection matches = urlRx.Matches(message); 
foreach (Match match in matches) 
{ 
    list.Add(match.Value); 
} 
return list; 

它给的网址,但不是代码的完整one.Output是

http://www.test.com/test.aspx

但是我们需要完整的网址,如

http://www.test.com/test.aspx?id=53

请建议如何解决issue.Thanks提前。

+0

看看这个[stackoverflow](http://stackoverflow.com/questions/2343177/regex-for-url-including-query-string)的问题,我相信它会解决你的问题。 – Bibhu 2012-02-03 07:24:53

+0

查看[这个页面](http://daringfireball.net/2010/07/improved_regex_for_matching_urls)获得一个完整的正则表达式,用于在reguler文本中查找和隐藏URL。如果你需要更简单的东西,我认为它的评论足够好,你应该能够适应你的具体情况。 – 2012-02-03 07:22:35

回答

14

试试这个正则表达式,返回查询字符串也

(http|ftp|https)://([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)? 

您可以测试它gskinner

+2

似乎有点过于明确。不会'(ftp | https?):// [^ \ s] +'工作吗? – 2012-02-03 09:35:37

+0

+1 @zapthedingbat这也可以 – 2012-02-03 09:39:05

7
public List<string> GetLinks(string message) 
{ 
    List<string> list = new List<string>(); 
    Regex urlRx = new Regex(@"((https?|ftp|file)\://|www.)[A-Za-z0-9\.\-]+(/[A-Za-z0-9\?\&\=;\+!'\(\)\*\-\._~%]*)*", RegexOptions.IgnoreCase); 

    MatchCollection matches = urlRx.Matches(message); 
    foreach (Match match in matches) 
    { 
     list.Add(match.Value); 
    } 
    return list; 
} 

var list = GetLinks("Hey yo check this: http://www.google.com/?q=stackoverflow and this: http://www.mysite.com/?id=10&author=me"); 

它会找到以下类型的链接:

http:// ... 
https:// ... 
file:// ... 
www. ... 
1

如果你稍后在你的代码中使用这个URL(提取一个部分,查询字符串等),请consi der使用

Uri类与HttpUtility助手。

它可以帮助您完成此操作。