我有带URL的文本,我需要用HTML A标记来包装它们,如何在c#中执行此操作?
示例,我有
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.
答案 0 :(得分:12)
您可以使用正则表达式。如果您需要更好的正则表达式,可以在此处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));
}