C#正則讓文本中的所有網址自動變成連接

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;

    }

發佈了35 篇原創文章 · 獲贊 2 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章