以纯文本格式查找URL并插入HTML A标记

Tom*_*mas 2 html c# text-manipulation

我有带URL的文本,我需要用HTML A标记来包装它们,如何在c#中做到这一点?

例如,我有

My text and url http://www.google.com The end.
Run Code Online (Sandbox Code Playgroud)

我想得到

My text and url <a href="http://www.google.com">http://www.google.com</a> The end.
Run Code Online (Sandbox Code Playgroud)

nhu*_*nhu 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));
}
Run Code Online (Sandbox Code Playgroud)