• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
wysky
博客园    首页    新随笔    联系   管理    订阅  订阅
转换链接的正则
转自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;

    }


posted on 2007-12-21 13:19  文's sky  阅读(653)  评论(1)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3