C#正则让文本中的所有网址自动变成连接

来源:互联网 发布:手机迅雷连不上网络 编辑:程序博客网 时间:2024/06/05 17:34
public static string ShowUrls(string text)
    {
            Regex linkRegex = new Regex(" href\\s*=\\s*(?:(?:\\\"(?<url>[^\\\"]*)\\\")|(?<url>[^\\s]* ))",
            RegexOptions.IgnoreCase | RegexOptions.Compiled);
       

        MatchCollection linkMatchs = linkRegex.Matches(text);

       string pattern = "";

       if (text.Contains("http:"))//匹配http:
         {
             pattern = @"(http|ftp|https):\/\/[\w]+(.[\w]+)([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])";
         }
         else {//匹配www:
             pattern = @"[\w]+(.[\w]+)([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])";
         }

        MatchCollection matchs;
        string clearText = Regex.Replace(text, "<[^>]*>",string.Empty, RegexOptions.Compiled);//清除html标记
        matchs = Regex.Matches(clearText, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
        bool flag = true;
        foreach (Match m in matchs)
        {
            string link = "<a href=\"" + m.ToString() + "\" target=\"_new\">" + m.ToString() + "</a>";
            if (linkMatchs.Count > 0)
            {
                foreach (Match linkMatch in linkMatchs)
                {
                    if (linkMatch.Value.IndexOf(m.Value) > -1)
                    {
                        flag = false;
                        break;
                    }
                }
            }           
            if(flag)
            {
                text = text.Replace(m.ToString(), link);
            }
           
        }
        return text;

    }

原创粉丝点击