使链接可单击,除非它们已在使用 C#

本文关键字:链接 单击 | 更新日期: 2023-09-27 18:37:16

我找到了一些使用正则表达式来检测文本段落中URL模式并添加HTML代码以使它们链接的示例。我对这种方法的问题是,有时,输入段落既包含以纯文本编写的 URL(我想将其转换为可点击),也包含一些已经具有链接标记的 URL。例如,考虑以下段落:

My favourite search engine is http://www.google.com but 
sometimes I also use <a href="http://www.yahoo.com">http://www.yahoo.com</a>

我只想转换谷歌链接,但保留两个雅虎链接。

我所追求的是一个 C# 函数,它使用正则表达式来检测 URL 并转换它们,但它忽略周围有"A"标记标记或已经在"A"标记内的 URL。

编辑

这是我到目前为止所拥有的:

PostBody = "My favourite search engine is http://www.google.com but sometimes I also use <a href='"http://www.yahoo.com'">http://www.yahoo.com</a>";
String pattern = @"http(s)?://(['w+?'.'w+])+([a-zA-Z0-9'~'!'@'#'$'%'^'&amp;'*'(')_'-'='+'''/'?'.':';''',]*)?";
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(pattern);
System.Text.RegularExpressions.MatchCollection matches = regex.Matches(PostBody);
for (int i = 0; i < matches.Count; i++)
{
  PostBody = PostBody.Replace(matches[i].Value, String.Format("<a href='"{0}'">{1}</a>", matches[i].Value, matches[i].Value));
}
ltrlPostBody.Text = PostBody;

这是我得到的(为了清楚起见,我将其分成多行):

My favourite search engine is 
<a href="http://www.google.com">http://www.google.com</a> 
but sometimes I also use 
<a href="<a href="<a href="http://www.yahoo.com">http://www.yahoo.com</a>">
<a href="http://www.yahoo.com">http://www.yahoo.com</a></a>">

我只想转换第一个链接(在这种情况下),因为它还没有成为链接标记的一部分。

使链接可单击,除非它们已在使用 C#

您还可以使用 HTML Agility Pack,它为您提供更多功能(例如,您不想逃跑)。

<script></script>
元素

和样式元素:

using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
namespace ConsoleApplication3 {
  class Program {
    static void Main(string[] args) {
      var text = @"My favourite search engine is http://www.google.com but 
sometimes I also use <a href=""http://www.yahoo.com"">http://www.yahoo.com</a>
<div>http://catchme.com</div>
<script>
  var thisCanHurt = 'http://noescape.com';
</script>";
      var doc = new HtmlDocument();
      doc.LoadHtml(text);
      var regex = new Regex(@"http(s)?://(['w+?'.'w+])+([a-zA-Z0-9'~'!'@'#'$'%'^'&amp;'*'(')_'-'='+'''/'?'.':';''',]*)?", RegexOptions.IgnoreCase);
      var nodes = doc.DocumentNode.SelectNodes("//text()");
      foreach (var node in nodes) {
        if (node.ParentNode != null && (node.ParentNode.Name == "a" || node.ParentNode.Name == "script" || node.ParentNode.Name == "style")) {
          continue;
        }
        node.InnerHtml = regex.Replace(node.InnerText, (match) => {
          return string.Format(@"<a href=""{0}"">{0}</a>", match.Value);
        });
      }
      var builder = new StringBuilder(100);
      using (var writer = new StringWriter(builder)) {
        doc.Save(writer);
      }
      var compose = builder.ToString();
    }
  }
}

如果您已经编写了正则表达式来确定何时使用锚标记包装文本,则可以使用正则表达式来确定您的输入是否匹配,通过 http://msdn.microsoft.com/en-us/library/sdx2bds0.aspx

可以做一些简单的事情

private string Pattern = "whateverregexpatternyouhavewritten";
private bool MatchesPattern(string input)
{
    return Regex.IsMatch(Pattern, input);
}