使用Asp.net C#替换字符串中的所有URL为“a href”链接

3

我目前正在显示一个字符串的内容,它被放在一个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\\~\\!\\@\\#\\$\\%\\^\\&amp;\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", 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来实现?

提前致谢。


一个示例会有所帮助。可能需要使用文字控件来显示字符串,以便将其解释为HTML。 - Sascha
1
非常相关:https://dev59.com/bXRA5IYBdhLWcg3w_DAw - naveen
我不确定我完全理解这个问题;所以您在页面上有一个包含需要使用JavaScript转换的URL列表的标签中的字符串?如果您能给出一个简单的例子,那将非常有帮助。 - shelleybutterfly
我修改了答案 :) - Attila
2个回答

3
在一个样本中,我使用了这个标记。
<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地址,是否正确替换为在新浏览器窗口中打开的链接进行了测试。

你可以通过Web请求测试URL,并仅在成功打开时进行替换。如果不是所有URL都匹配,则可能需要更改正则表达式。

如果这不能回答你的问题,那么你应该添加一些更多的细节信息。


它能工作,但不完全。它不能处理带有“-”或“?ID=1988&”等其他情况的URL。我已经更新了我的答案,并提供了一个可能的正则表达式过滤器,你有什么想法如何实现它? - Attila
试着使用这个正则表达式:https?://[^\s]*匹配以http开头,后跟可选的字母s,再后跟任何非空白字符的字符串。 - Sascha


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接