我目前正在 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"
我使用了以下代码,但它不适用于每个网址:
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 开头的所有内容放入(不包括)第一个空格?在那种情况下,我如何使用 .replace 来实现这一点?
提前发送。
最佳答案
在示例中我使用了这个标记
<body>
<form id="form1" runat="server">
<div>
<asp:Literal ID="litTextWithLinks" runat="server" />
</div>
</form>
</body>
连同代码隐藏
private const string INPUT_STRING = "Bla bla bla bla http://www.site.com and bla bla http://site2.com blabla";
protected void Page_Load ( object sender, EventArgs e ) {
var outputString = INPUT_STRING;
Regex regx = new Regex( @"https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?", RegexOptions.IgnoreCase );
MatchCollection mactches = regx.Matches( INPUT_STRING );
foreach ( Match match in mactches ) {
outputString = outputString.Replace( match.Value, String.Format( "<a href=\"{0}\" target=\"_blank\">{0}</a>", match.Value ) );
}
litTextWithLinks.Text = outputString;
}
对于样本中的所有 URL,其中正确替换为在新浏览器窗口中打开的链接。
您可以通过执行 WebRequest 来测试 url,并且仅在打开成功时才替换。如果并非所有 URL 都匹配,那么您可能需要更改正则表达式。
如果这不能回答您的问题,您应该添加更多详细信息。
关于c# - Asp.net C# 用 "a href"链接替换字符串的所有 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7062448/