用于链接字符串中URL的C#代码

Van*_*ith 31 c# regex asp.net linkify

有没有人有任何好的c#代码(和正则表达式)将解析字符串并"链接"可能在字符串中的任何网址?

Kon*_*kus 45

这是一个非常简单的任务,你可以用Regex和一个随时可用的正则表达式来实现它:

就像是:

var html = Regex.Replace(html, @"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+" +
                         "\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?" +
                         "([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$",
                         "<a href=\"$1\">$1</a>");
Run Code Online (Sandbox Code Playgroud)

您可能不仅对创建链接感兴趣,还对缩短URL感兴趣.这是一篇关于这个主题的好文章:

另见:

  • 好东西!但是,要使用.Net Regex(System.Text.RegularExpressions.Regex),并使用位于文本行中间的url,我需要修改代码,如下所示:Regex.Replace(answer,@"(( HTTP | HTTPS | FTP)\:// [A-ZA-Z0-9\ - \] +\[A-ZA-Z] {2,3}(:[A-ZA-Z0-9]*)?/?([a-zA-Z0-9\ - \._ \?\,\'/ \\\ +&amp;%\ $#\ =〜])*)",@"<a href = '$ 1'> $ 1 </A>"); (9认同)
  • 我使用以下正则表达式来说明不完全限定的主机名:`@“((http | https | ftp)\:// [a-zA-Z0-9 \-\。] +(\。[ a-zA-Z] {2,3})?(:[a-zA-Z0-9] *)?/?([a-zA-Z0-9 \-\ ._ \?\,\'/ \\\ +&amp;%\ $#\ =〜])*)“` (3认同)
  • 你好 很好的回应。您的帖子(和链接)中的大多数建议似乎都有效,但它们似乎都破坏了正在评估的文本中的所有现有链接。 (2认同)
  • 嗯,效果很好。从而证明我们在这里提出的所有要点;) (2认同)

jos*_*sno 11

好吧,经过大量的研究,以及几次尝试修复时间

  1. 人们在同一篇文章中输入http://www.sitename.com和www.sitename.com
  2. 固定到parenthisis等(http://www.sitename.com)和http://msdn.microsoft.com/en-us/library/aa752574(vs.85).aspx
  3. 很长的URL,如:http://www.amazon.com/gp/product/b000ads62g/ref=s9_simz_gw_s3_p74_t1?pf_rd_m=atvpdkikx0der&pf_rd_s=center-2&pf_rd_r=04eezfszazqzs8xfm9yd&pf_rd_t=101&pf_rd_p=470938631&pf_rd_i=507846

我们现在正在使用这个HtmlHelper扩展...想我会分享并得到任何评论:

    private static Regex regExHttpLinks = new Regex(@"(?<=\()\b(https?://|www\.)[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|](?=\))|(?<=(?<wrap>[=~|_#]))\b(https?://|www\.)[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|](?=\k<wrap>)|\b(https?://|www\.)[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]", RegexOptions.Compiled | RegexOptions.IgnoreCase);

    public static string Format(this HtmlHelper htmlHelper, string html)
    {
        if (string.IsNullOrEmpty(html))
        {
            return html;
        }

        html = htmlHelper.Encode(html);
        html = html.Replace(Environment.NewLine, "<br />");

        // replace periods on numeric values that appear to be valid domain names
        var periodReplacement = "[[[replace:period]]]";
        html = Regex.Replace(html, @"(?<=\d)\.(?=\d)", periodReplacement);

        // create links for matches
        var linkMatches = regExHttpLinks.Matches(html);
        for (int i = 0; i < linkMatches.Count; i++)
        {
            var temp = linkMatches[i].ToString();

            if (!temp.Contains("://"))
            {
                temp = "http://" + temp;
            }

            html = html.Replace(linkMatches[i].ToString(), String.Format("<a href=\"{0}\" title=\"{0}\">{1}</a>", temp.Replace(".", periodReplacement).ToLower(), linkMatches[i].ToString().Replace(".", periodReplacement)));
        }

        // Clear out period replacement
        html = html.Replace(periodReplacement, ".");

        return html;
    }
Run Code Online (Sandbox Code Playgroud)


Van*_*ith 6

protected string Linkify( string SearchText ) {
    // this will find links like:
    // http://www.mysite.com
    // as well as any links with other characters directly in front of it like:
    // href="http://www.mysite.com"
    // you can then use your own logic to determine which links to linkify
    Regex regx = new Regex( @"\b(((\S+)?)(@|mailto\:|(news|(ht|f)tp(s?))\://)\S+)\b", RegexOptions.IgnoreCase );
    SearchText = SearchText.Replace( "&nbsp;", " " );
    MatchCollection matches = regx.Matches( SearchText );

    foreach ( Match match in matches ) {
        if ( match.Value.StartsWith( "http" ) ) { // if it starts with anything else then dont linkify -- may already be linked!
            SearchText = SearchText.Replace( match.Value, "<a href='" + match.Value + "'>" + match.Value + "</a>" );
        }
    }

    return SearchText;
}
Run Code Online (Sandbox Code Playgroud)