2011-03-07 55 views
2

我有带有URL的文本,我需要用HTML包装它们标记,如何在c#中执行此操作?以纯文本格式查找网址并插入HTML A标记

例如,我有

My text and url http://www.google.com The end. 

我想获得

My text and url <a href="http://www.google.com">http://www.google.com</a> The end. 
+4

什么方法(ES)你试过这么远吗? – 2011-03-07 11:03:53

回答

11

您可以使用正则表达式这一点。如果你需要一个更好的正则表达式,你可以搜索在这里http://regexlib.com/Search.aspx?k=url

我给这家快速的解决办法是这样的:

string mystring = "My text and url http://www.google.com The end."; 

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

MatchCollection matches = urlRx.Matches(mystring); 

foreach (Match match in matches) 
{ 
    var url = match.Groups["url"].Value; 
    mystring = mystring.Replace(url, string.Format("<a href=\"{0}\">{0}</a>", url)); 
} 
+0

谢谢你的工作。 – PrateekSaluja 2012-02-01 05:47:12