现在的位置: 首页 > 综合 > 正文

转换链接的正则

2013年06月18日 ⁄ 综合 ⁄ 共 1400字 ⁄ 字号 评论关闭
转自http://www.cnblogs.com/dudu/archive/2007/12/19/1006119.html,收藏一下.
    public static string ShowUrls(string text)
    
{
        
//代码来自博客园 http://www.cnblogs.com
        Regex linkRegex = new Regex(" href\\s*=\\s*(?:(?:\\\"(?<url>[^\\\"]*)\\\")|(?<url>[^\\s]* ))",
            RegexOptions.IgnoreCase | RegexOptions.Compiled);
        
        MatchCollection linkMatchs 
= linkRegex.Matches(text);
        
        
string pattern = @"(http|ftp|https):\/\/[\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;

    }

抱歉!评论已关闭.