我目前正在显示一个字符串的内容,它被放在一个pre标签里面。但是我需要编写一个函数,对于字符串中的每个链接都用链接标签来替换它,我尝试了几种字符串替换和正则表达式方法,但都不能有效实现。
string myString = "Bla bla bla bla http://www.site.com and bla bla http://site2.com blabla"
//Logic
string outputString = "Bla bla bla bla <a href="http://www.site.com" target="blank">http://www.site.com</a> and bla bla <a href="http://site2.com" target="blank">http://site2.com</a> blabla"
我使用了以下代码,但它并不适用于每个url:
string orderedString = item.Details.Replace("|", "\n" );
string orderedStringWithUrl = "";
System.Text.RegularExpressions.Regex regx = new System.Text.RegularExpressions.Regex("http://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.MatchCollection mactches = regx.Matches(orderedString);
foreach (System.Text.RegularExpressions.Match match in mactches)
{
orderedStringWithUrl = orderedString.Replace(match.Value, "<a href='" + match.Value + "' target='blank'>" + match.Value + "</a>");
}
有什么建议吗?
更新: 我注意到字符串中的URL都没有空格,且都以http或https开头。 是否可以将以http或https开头的所有内容放入<a>标签中,直到(但不包括)第一个空格为止?如果是这样,我该如何使用.replace来实现?
提前致谢。