从文本中获取url
可能重复:
URL的正则表达式,包括查询字符串
我有一个文字或信息。
嘿! 试试这个http://www.test.com/test.aspx?id=53
我们的要求是从文本中获取链接。我们正在使用以下代码
List list = new List(); Regex urlRx = new Regex(@"(?(http:|https:[/][/]|www.)([az]|[AZ]|[0-9]|[/.]|[~])*)", RegexOptions.IgnoreCase); MatchCollection matches = urlRx.Matches(message); foreach (Match match in matches) { list.Add(match.Value); } return list;
它给出了url但不是完整的。代码的输出是
http://www.test.com/test.aspx
但我们需要完整的url
http://www.test.com/test.aspx?id=53
请建议如何解决该问题。谢谢。
试试这个正则表达式,也返回查询字符串
(http|ftp|https)://([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?
你可以在gskinner上测试它
public List GetLinks(string message) { List list = new List (); 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. ...
如果您稍后在代码中使用此URL(提取部件,查询字符串等),请考虑使用
Uri
类与HttpUtility
助手结合使用。
它可以帮助您完成此操作。